多个联接同名Laravel

多个联接同名Laravel

我有一个问题,我有4张桌子

Deals
Lists
Lists_Galleries
List_has_deals
Lists_has_gallery


我需要从交易中获取img_src_list,它在List_Galleries中是什么。

我这次有这个变种

$query = ListsDeals::where( $matchDeals )
                    ->where('stock', '>', 0)
                    ->orwhere( $matchOtherDeals )
                    ->whereDate('end_date', '>', date('Y-m-d'))
                    ->limit( 4 )
                    ->offset( 0 )
                    ->orderBy( 'start_date' );

$deals = $query->join( 'list_has_deals', 'deals.id', '=', 'list_has_deals.deal_id'  )
        ->join( 'lists', 'list_has_deals.list_id', '=', 'lists.id' )
        ->join( 'list_has_gallery', 'lists.id', '=', 'list_has_gallery.list_id' )
        ->join( 'lists_galleries', 'list_has_gallery.gallery_id', '=', 'lists_galleries.id' )->get();


这给了我结果,但是我如何在所有表中都具有相同的名称,例如交易的标题和覆盖名称的列表并没有正确获得值,我如何获得某些列而不会覆盖其他列?问候。

更新

对于所有结果,这总是给我相同的待遇。

$deals = $query->join( 'list_has_deals', 'deals.id', '=', 'list_has_deals.deal_id'  )
        ->join( 'lists', 'list_has_deals.list_id', '=', 'lists.id' )
        ->join( 'list_has_gallery', 'lists.id', '=', 'list_has_gallery.list_id' )
        ->join( 'lists_galleries', 'list_has_gallery.gallery_id', '=', 'lists_galleries.id' )
        ->select([ 'deals.id as deal_id', 'deals.stock as stock', 'deals.price as price', 'deals.price_reduced as price_reduced', 'deals.img_src as img_src', 'deals.title_deal as deal_title' ])->get();


更新

$deals = $query->join( 'list_has_deals', 'deals.id', '=', 'list_has_deals.deal_id'  )
        ->join( 'lists', 'list_has_deals.list_id', '=', 'lists.id' );

    $other = $deals->join( 'list_has_gallery', 'lists.id', '=', 'list_has_gallery.list_id' )
        ->join( 'lists_galleries', 'list_has_gallery.gallery_id', '=', 'lists_galleries.id' )
        ->select([ 'deals.id', 'deals.stock', 'deals.price', 'deals.price_reduced', 'deals.img_src', 'deals.title_deal', 'lists_galleries.img_src_list' ])
        ->addSelect([ 'lists_galleries.img_src_list' ])
        ->get();

最佳答案

您可以使用select()仅选择所需的列,并使用别名重命名任何冲突的列:

$query->select(['lists.title AS title', 'lists_galleries.name AS name', 'lists.id AS id'])->get();


这样,您可以只挑选所需的列并轻松处理冲突。

关于php - 多个联接同名Laravel,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45847493/

10-11 05:21