php - 使用 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);
}])
但它没有用。
我确定这应该是编写此代码的更好方法,但不知道如何
解决方案
尝试这个
Charging::with('some.ports', 'shares')->with('chargingComments.user')->with('chargingComments.car')->find($id)->latest()->take(10)->get();
推荐阅读
- c++ - 覆盖 + 运算符和 += 运算符
- apache-spark - 如何在 Spark sql 中将 DDMMMYYYY HH:mm:ss:ssssss 格式的时间戳更改为 yyyy-MM-dd 格式
- javascript - 带参数的 gatsby 查询
- informatica-powercenter - Informatica PowerCenter Designer 表达式工具箱
- prometheus - 如何用 1 个 sql-query 定义多个图
- caching - NUXT.JS 存储/缓存 API 请求
- java - 将 12 小时时间格式转换为 24 小时格式
- c - 输出如何 1 和 4 。我无法理解c程序背后的逻辑?
- gcc - GCC 库中不存在 libstdc++.a
- javascript - How can make a list from matrix in javascript?