Laravel有条件地根据指定的类连接表

时间:2016-05-23 10:22:29

标签: mysql laravel query-builder

我有三个表customersorganizationscontacts。表customers表包含列customer_class(类表示表使用OrganizationContact)和customer_id(对应于id中的列organizations {1}}或contacts)。

所以我做的是

$interactions = DB::table('sales_interactions')
->join('customers', 'customers.id', '=', 'sales_interactions.customer_id')
->join('organizations', function($join)
{
    $join->on('customers.customer_id', '=', 'organizations.id')
        ->where('customers.customer_class', '=', 'Organization');       
})
->join('contacts', function($join)
{
    $join->on('customers.customer_id', '=', 'contacts.id')
        ->where('customers.customer_class', '=', 'Contact');       
})

->select([
    'organizations.title as customer',
    'contacts.name as customer',
    'sales_interactions.id',
    'sales_interactions.created_at',
    'sales_interactions.title',
    'status',
    'deadline',
    'value',
]);

仅在我加入组织时才有用。但加入联系人会返回零结果。

2 个答案:

答案 0 :(得分:0)

您需要一个联合查询:

    $contactsQuery = DB::table('sales_interactions')
        ->join('customers', 'customers.id', '=', 'sales_interactions.customer_id')
        ->join('contacts', function($join)
        {
            $join->on('customers.customer_id', '=', 'contacts.id')
                ->where('customers.customer_class', '=', 'Contact');
        })
        ->select([
            'contacts.name as customer',
            'sales_interactions.id',
            'sales_interactions.created_at',
            'sales_interactions.title',
            'status',
            'deadline',
            'value',
        ]);

    $interactions = DB::table('sales_interactions')
        ->join('customers', 'customers.id', '=', 'sales_interactions.customer_id')
        ->join('organizations', function($join)
        {
            $join->on('customers.customer_id', '=', 'organizations.id')
                ->where('customers.customer_class', '=', 'Organization');
        })
        ->select([
            'organizations.title as customer',
            'sales_interactions.id',
            'sales_interactions.created_at',
            'sales_interactions.title',
            'status',
            'deadline',
            'value',
        ])
        ->union($contactsQuery)
        ->get();

答案 1 :(得分:0)

在laravel doc中查看Polimorphic relationship。我建议使用laravel orm,因为它非常好而且容易。您正在寻找的可以进行简单的查询。