簡體   English   中英

Laravel 通過數據庫查詢生成器獲得一對多限制

[英]Laravel get one to many with limit by DB query builder

我有一個通過 model_has_attachments 與附件表連接的產品表。 我需要將第一個附件連接到查詢生成器中的每個產品記錄,但由於某種原因,它只給我一些帶有 model_has_attachments id 的記錄,而 rest 是 null

我的查詢生成器看起來像:

$products = DB::table('products')->
leftJoin(DB::raw('(select `model_id`, `attachment_id` from model_has_attachments where model_has_attachments.model_id = id) as model_has_attachments'), 'model_has_attachments.model_id', 'products.id')->
leftJoin('attachments', 'model_has_attachments.attachment_id', '=', 'attachments.id')->
            select('products.id', 'products.square', 'products.height', 'products.address', 'products.rooms', 'products.title', 'products.description', 'model_has_attachments.model_id as id_model', 'model_has_attachments.attachment_id')->
            where([
            ['products.deleted_at', '=', null],
        ]);

我試圖在DB::raw中添加limit = 1但它只給我產品表的第一條記錄,而不是連接表。 你能告訴我為什么嗎?

我也嘗試了不同的方法,但它會獲取所有附件的記錄,如果產品有多個附件,則會導致重復的產品記錄。 我也嘗試在末尾添加->limit(1)但它只是忽略了該方法。

leftJoin('model_has_attachments', function ($join) {
    $join->on('products.id', '=', 'model_has_attachments.model_id')->where('model_has_attachments.model_type', '=', Product::class);
})->
``
//try this

$products = Product::leftJoin('model_has_attachments', 'products.id', '=', 'model_has_attachments.model_id')
    ->leftJoin('attachments', 'attachments.id', '=', 'model_has_attachments.attachment_id')
    ->addSelect('products.*', 'attachments.id as attachment_id')
    ->where('attachments.is_active',1)
    ->get();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM