php - Laravel: One relation, multiple models
Get the solution ↓↓↓I have a model "User", and each user has "Posts". Now there are different types of posts, like "TextPost", "VideoPost", etc.
I want to get all posts of a user like this:
$user->posts()->get()
This should return an array of objects with the correct class, so e.g. an array like this:
[App\VideoPost{}, App\TextPost{}]
I tried to use polymorphic relationships as described in the docs, but it doesn't work. Any ideas?
Answer
Solution:
There isn't really a relationship type in Laravel for your specific use case. The easiest thing you can do in this case is create a separate hasMany relationship for each of your post types, and then write a function that returns a combination of all the results.
So you'd end up with something like this in your User class:
public function videoPosts()
{
return $this->hasMany(App\VideoPost::class);
}
public function textPosts()
{
return $this->hasMany(App\TextPost::class);
}
public function getPosts()
{
return $this->textPosts->concat($this->videoPosts);
}
You can then just keep chaining concat calls for every other post type you may want to add.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: err_ossl_pem_no_start_line
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.