亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何獲取項目不在 Laravel Eloquent 的集合中?

如何獲取項目不在 Laravel Eloquent 的集合中?

PHP
偶然的你 2023-04-02 10:39:08
在我的 Laravel 6.x 項目中,我有Product模型Warehouse和WarehouseProduct模型。在產品中,我存儲了我產品的基本信息。在 WarehouseProduct 中,我存儲有關倉庫中產品的庫存量信息。當然,我有很多倉庫,里面有很多產品。我的Product樣子是這樣的:class Product extends Model{    protected $fillable = [        'name',        'item_number',        // ...    ];}看起來Warehouse像這樣:class Warehouse extends Model{    protected $fillable = [        'name',        'address',        // ...    ];    public function products() {        return $this->hasMany(WarehouseProduct::class);    }    public function missingProduct() {        // here I need to return a Product collection which are not in this Warehouse or the        // stored amount is 0    }}最后WarehouseProduct看起來像這樣:class WarehouseProduct extends Model{    protected $fillable = [        'product_id',        'warehouse_id',        'amount',        // ...    ];    public function product() {        return $this->belongsTo(Product::class, 'product_id');    }    public function warehouse() {        return $this->belongsTo(Warehouse::class, 'warehouse_id');    }我怎樣才能得到一個Product沒有存儲在 aWarehouse或數量是的集合0?
查看完整描述

2 回答

?
慕田峪9158850

TA貢獻1794條經驗 獲得超7個贊

這樣的事情應該有效:


use App\Product;


public function missingProduct() {

    $excludedProducts = $this->products()->where('amount', '>', 0)->pluck('id');


    return Product::whereNotIn('id', $excludedProducts)->get();

}

基于@KarolSobański 的解決方案,當您warehouse_products向產品模型添加關系時:


use App\Product;

use Illuminate\Database\Eloquent\Builder;


public function missingProduct() {

    return Product::whereDoesntHave('warehouse_products', function (Builder $query) {

        $query->where('warehouse_id', $this->id);

    })->orWhereHas('warehouse_products', function (Builder $query) {

        $query->where('warehouse_id', $this->id);

        $query->where('amount', 0);

    })->get();

}


查看完整回答
反對 回復 2023-04-02
?
料青山看我應如是

TA貢獻1772條經驗 獲得超8個贊

最短的答案可能與此類似:


Product::doesntHave('warehouse_products')

       ->orWhereHas('warehouse_products', function (Builder $query) {

           $query->where('amount', '=', 0)

       })->get();

雖然我不確定以上是否有效。


但以下較長的查詢肯定可以解決問題:


Product::where(function ($query) {

    $query->doesntHave('warehouse_products');

})->orWhere(function ($query) {

    $query->whereHas('warehouse_products', function (Builder $query) {

       $query->where('amount', '=', 0);

    });

})->get();


查看完整回答
反對 回復 2023-04-02
  • 2 回答
  • 0 關注
  • 119 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號