选择带有用户数据的评论和使用 Laravel 附加评论的最佳方法是什么?



我试图用注释(包括有关用户及其汽车的数据(制作列表,这些注释存储在另一个表中。

控制器包含以下查询:

Charging::available()
->with('some.ports', 'shares')
->find($id);

我把它改写成这样:

Charging::available()
->with('some.ports', 'shares')
->with('chargingComments.user')
->with('chargingComments.car')
->find($id);

这就是ChargingComments模型的样子:

public function comments() {
return $this->belongsTo(AppModelsCharging::class);
}
public function user() {
return $this->belongsTo(AppModelsUser::class);
}
public function car() {
// here 'id' is the row in the table with users cars
// 'car_id' is in the table with comments  
return $this->hasOne(AppModelsUserCar::class, 'id', 'car_id');
}

它向我返回有关每个评论的用户和他的汽车的数据,但顺便说一句,我必须以某种方式将结果限制为 10 行。我试图添加

'user' => function($query) {
return $query->take(10);
}])

但它没有用。

我确定这应该是编写此代码的更好方法,但不知道如何

试试这个

Charging::with('some.ports', 'shares')->with('chargingComments.user')->with('chargingComments.car')->find($id)->latest()->take(10)->get();

最新更新