首页 > 解决方案 > 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();

标签: phplaravelrelationship

解决方案


使用HasManyThrough

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');
}    

推荐阅读