![](/img/trans.png)
[英]how to get all comments with their post title linked to posts table in laravel?
[英]How to use print all comments for respective posts using relationship in Laravel 8
我正在尝试使用该关系打印每个帖子的所有评论,
错误: Eloquent 构建器实例上不存在属性 [comments]。
发布 Model
class WorkTravel extends Model
{
use HasFactory;
protected $table = 'work_travel';
protected $fillable = ['name', 'role', 'location','salary','application_deadline','position','description'];
public function comments()
{
return $this->hasMany(CommentWorkTravel::class);
}
}
评论 Model
class CommentWorkTravel extends Model
{
use HasFactory;
protected $table = 'comments_for_work_travel';
protected $fillable = ['message'];
public function workTravel()
{
return $this->belongsTo(WorkTravel::class);
}
}
Controller
public function index(){
$work_travels=WorkTravel::select('id','name','role','application_deadline')
->comments()
->paginate(6);
dd($work_travels);
//Error: Call to undefined method \Database\Eloquent\Builder::comments().
只需使用 ->comments 的->comments
->comments()
insted 由于所有关系也用作查询构建器,因此您可以通过调用 comments 方法并继续将条件链接到查询上来为关系查询添加进一步的约束:
你的代码应该是这样的
public function index(){
$work_travels=WorkTravel::select('id','name','role','application_deadline')
->comments()
->paginate(6);
dd($work_travels);
错误
Eloquent 构建器实例上不存在属性 [comments]。
表示您正在尝试从不是 model 实例的东西中接收值。
看你的线
$work_travels=WorkTravel::select('id','name','role','application_deadline')
->comments
->paginate(6);
您正在选择一行“WorkTravel”类型,而不是调用属性“comments”(末尾没有 ())。 但是你得到的是 model 中定义的关系,而不是具有该关系的查询的结果。
它像这样工作
Model->relationshipmethod()->where('something,'searchvalue')->get()
或者
Model->relationshipmethod()->all()
如果您想将行用于分页表 laravel 还提供了 paginate 方法,该方法将接收行的子集并将用于获取上一页和下一页的信息附加到返回的集合中。
Model->relationshipmethod()->paginate()
要测试您应该修改您的语句以使用真正的 model 和在该 model 中定义的关系方法。 不是 select 方法
$WorkTravelID = 1; // get that from somewhere
$WorkTravel = \App\Models\WorkTravel::find($WorkTravelID);
$work_travels = $WorkTravel->comments()->paginate(6);
dd($work_travels);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.