Reputation: 85
i have three models
Article
id
title
Comment
id
title
user_id
article_id
User
id
name
what i wanna achieve is to select one article based on its id with comments and user info that made that comment
like that :
$article = Article::find($id -- say 1)->with('comments' -- this is a relation in Article Model)->get();
this gives me article with related comments as an array of objects say comment one - comment two etc ....
what i want instead of user_id in comment object i wanna it to be a user object
see this pic thats what i reached so far
using laravel 5.4
Upvotes: 1
Views: 16281
Reputation: 342
It is far better to use ->find() at last instead of ->get() because get() returns a Collection.
This way you will get a single object which you want instead of a Collection.
For example:
$commentableObj = Post::with(['comments'])
->withCount(['comments'])
->findOrFail($commentable->id);
Upvotes: 0
Reputation: 199
If you have defined the foreign key relationship in Schemas, you can define functions for Eloquent Relationship as defined in following reference link - Laravel - Eloquent Relationships.
You can define functions in models as follows -
Article -
class Article extends Model
{
...
public function comments(){
// Accessing comments posted to that article.
return $this->hasMany(\App\Comment::class);
}
// Create a foreign key to refer the user who created the article. I've referred it here as 'created_by'. That would keep relationship circle complete. You may ignore it if you want.
public define user(){
// Accessing user who posted the article
return $this->hasOne(\App\User::class, 'id', 'created_by');
}
}
Comment -
class Comment extends Model
{
...
public function article(){
// Accessing article to which the particular comment was posted
return $this->hasOne(\App\Article::class, 'id', 'article_id');
}
public function user(){
// Accessing user who posted the comment
return $this->hasOne(\App\User::class, 'id', 'user_id');
}
}
User -
class User extends Models
{
...
public function articles(){
// Accessing articles posted by a user
return $this->hasMany(\App\Article::class);
}
public function comments(){
// Accessing comments posted by a user
return $this->hasMany(\App\Comment::class);
}
}
Now you can use like following -
$article = Article::findOrFail($id);
$comments = $article->comments;
$article_user = $article->user;
$comment_user = Comment::findOrFail($commnet_id)->user;
$users_comments = User::findOrFail($user_id)->comments;
$users_articles = User::findOrFail($user_id)->articles;
and so on...
Upvotes: 3
Reputation: 1186
You can use following:
$articles = Article::find($id)->with('comments', 'comments.user')->get();
Here 'user' is the relationship you mentioned in the comments model for User.
Upvotes: 9