How can I join in Laravel to get data?
I’m working with Laravel 5 and I’ve the following models
Group.php
class Group extends Model
{
protected $fillable = ([
'id'
]);
public function users(){
return $this->belongsToMany(
'AppUser',
'user_group'
);
}
public function posted(){
return $this->hasMany(
'AppPostGroup'
);
}
}
PostGroup.php
class PostGroup extends Model
{
protected $fillable = [
'group_id', 'user_id', 'post_content'
];
public function user(){
return $this->belongsTo('AppUser');
}
public function group(){
return $this->belongsTo('AppGroup');
}
public function commented(){
return $this->hasMany(
'AppPostComment'
);
}
}
PostComment.php
class PostComment extends Model
{
protected $fillable = [
'post_id', 'user_id', 'comment_content'
];
public function post(){
return $this->belongsTo('AppPostGroup');
}
public function user(){
return $this->belongsTo('AppUser');
}
}
Contextually, my web application presents groups
, in which you can create posts
and to which post you can write comments
. So, I have the following relationships in my database:
- Group: (id, name, description);
- PostGroup: (id, group_id, user_id, post_content);
- PostComment: (id, post_id, user_id, comment_content);
What I want to do is to create a list of PostComment objects, and then make a query to get all the comments of all the posts of a group, in MySQL looks like:
SELECT post_comment.* FROM post_comment,post_group WHERE post_comment.post_id = post_group.id AND post_groups.group_id = 1;
Now, for example, in Laravel if I wanna get all the posts of a group I’ve the following code line:
$postList = Group::find($id)->posted->sortByDesc('created_at');
Where posted
is a function in Group Modal. I tried to do something like
$commentList = PostGroup::where('group_id', $id)->commented;
But it doesn’t work, how can I solve?
from Laravel Questions and Answers https://laravelquestions.com/php/how-can-i-join-in-laravel-to-get-data/
via Lzo Media
No comments:
Post a Comment