目前我有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
d更喜欢能够做这样的事情:
$transaction_id = $id;
$listing = Listing::whereHas('payment', function($q) use ($id) {
$q->where('transaction_id', $id);
$q->where('user_id', Auth::user()->id);
})->first();
答案 0 :(得分:1)
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');
}