首页 > 解决方案 > 使用 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(\App\Models\Charging::class);
}

public function user() {
    return $this->belongsTo(\App\Models\User::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(\App\Models\UserCar::class, 'id', 'car_id');
}

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

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

但它没有用。

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

标签: phplaravel

解决方案


尝试这个

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

推荐阅读