gpt4 book ai didi

php - 如何加入 Laravel 获取数据?

转载 作者:行者123 更新时间:2023-11-29 04:33:55 24 4
gpt4 key购买 nike

我正在使用 Laravel 5,我有以下模型

组.php

class Group extends Model
{

protected $fillable = ([
'id'
]);

public function users(){
return $this->belongsToMany(
'App\User',
'user_group'
);
}

public function posted(){
return $this->hasMany(
'App\PostGroup'
);
}
}

PostGroup.php

class PostGroup extends Model
{
protected $fillable = [
'group_id', 'user_id', 'post_content'
];

public function user(){
return $this->belongsTo('App\User');
}

public function group(){
return $this->belongsTo('App\Group');
}

public function commented(){
return $this->hasMany(
'App\PostComment'
);
}
}

PostComment.php

class PostComment extends Model
{
protected $fillable = [
'post_id', 'user_id', 'comment_content'
];

public function post(){
return $this->belongsTo('App\PostGroup');
}

public function user(){
return $this->belongsTo('App\User');
}

}

在上下文中,我的 Web 应用程序提供了 groups,您可以在其中创建 posts 并且您可以在其中写 comments。所以,我的数据库中有以下关系:

  • 组:(id、名称、描述);
  • 帖子组:(id, group_id, user_id, post_content);
  • 发表评论:(id, post_id, user_id, comment_content);

我想做的是创建一个PostComment对象列表,然后进行查询获取一个组所有帖子的所有评论,在MySQL 看起来像:

SELECT post_comment.* FROM post_comment,post_group WHERE post_comment.post_id = post_group.id AND post_groups.group_id = 1;

现在,例如,在 Laravel 中,如果我想获取一个组的所有帖子,我有以下代码行:

$postList = Group::find($id)->posted->sortByDesc('created_at');

posted 是 Group Modal 中的一个函数。我试着做类似的事情

$commentList = PostGroup::where('group_id', $id)->commented;

但是还是不行,请问怎么解决?

编辑

组 Controller .php

/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
// Replace with shares of publication-group-model
$authUser = Auth::user();
$sharesList = Group::find($id)->shares->sortByDesc('created_at');
$groupList = $authUser->groupsAsMember->where('id', '<>', $id);
$group = $authUser->groups->find($id);
$postList = Group::find($id)->posted->sortByDesc('created_at');

$postsGroups = PostGroup::where('group_id', $id)->with('commented')->get();

//dd($postsGroups);

foreach ($postsGroups as $postGroup) {
$commentsList = $postGroup->commented;
}

//dd($commentsList);

return view('Pages.Group.detail', ['sharesList' => $sharesList, 'groupList' => $groupList, 'theGroup' => $group, 'postList' => $postList, 'commentsList' => $commentsList]);
}

最佳答案

Eloquent 的 HasManyThrough关系是为这种情况设计的,以允许访问远距离关系:

class Group extends Model
{
public function comments()
{
return $this->hasManyThrough(
PostComment::class,
PostGroup::class,
'group_id',
'post_id',
'id',
'id'
);
}
}

关于php - 如何加入 Laravel 获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50159897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com