php - Laravel 5中的子关系?
问题描述
目前我有 3 个模型,列表,报价和付款,它们具有以下关系:
清单
class Listing extends Model {
public function offers() {
return $this->hasMany(\App\Models\Offer::class)->orderBy('created_at', 'desc');
}
}
提供
class Offer extends Model {
public function payment() {
return $this->hasOne(\App\Models\Payment::class, 'item_id', 'id')->where('item_type', \App\Models\Offer::class)->where('status', '1');
}
public function listing() {
return $this->belongsTo(\App\Models\Listing::class)->withTrashed();
}
}
支付
class Payment extends Model {
public function offer() {
return $this->belongsTo(\App\Models\Offer::class, 'item_id', 'id')->withTrashed();
}
}
我怎样才能从他们列出模型并直接返回与付款表的关系?
列表可以有无限数量的优惠,但优惠只能有 1 最大付款
要查找任何相应的付款信息,我必须根据模型内的 查询报价listing_id
,然后访问Offer->payment
,当我更希望能够执行以下操作时:
$transaction_id = $id;
$listing = Listing::whereHas('payment', function($q) use ($id) {
$q->where('transaction_id', $id);
$q->where('user_id', Auth::user()->id);
})->first();
解决方案
public function payments() {
return $this->hasManyThrough(Payment::class, Offer::class, null, 'item_id')
->where('payments.item_type', Offer::class)
->where('payments.status', '1')
->orderBy('offers.created_at', 'desc');
}
推荐阅读
- javascript - 自定义js选择下拉选项不变
- excel-dna - ExcelDna xll 插件未显示,但功能可见,为什么?
- python - Python 附加到 .txt
- r - 将列的相似值组合成行
- mysql - 为什么我的查询返回正确的最大值而不是与该平均值对应的名称?
- php - 如何在 VPS 上的 phpMyAdmin 或 SSH 中创建预定事件?
- shiny - 如何按顺序执行闪亮的模块?
- node.js - 致命:无效的参考规范(Heroku nodejs)
- hadoop - Cloudera 安装期间出现错误,提示未找到在主机服务器上运行的数据库服务器
- java - LibGDX:在另一个线程中创建新的 scene2d 对象?