duanchique1196 2017-07-28 09:22
浏览 44
已采纳

Laravel Eloquent,多个模式查询

I have the below query (simplified):

$q = ModelOne::with('relation_one', 'relation_two')
    ->whereHas('relation_three', function ($q) {
        $q->where('object', 'Obj1');
    })
    ->whereHas('relation_four', function ($q) {
        $q->where('object', 'Obj2');
    })
    ->get();`

It loads the relation_one and relation_two relationships fine, I also need to load another relationship per row, either relation_three or relation_four depending on the value of ModelOne->object.

The issue I am having is that ModelOne is from schema1 and the tables used in relation_three & relation_four are from schema2.

Both models are set up correct with their individual protected $connection and protected $table variables.

The error I am recieving is that the tables for relationship_three or relationship_four does not exist as the sub-query is checking the wrong schema.

Can anyone suggest how to fix this? Have had a look through the docs but couldn't find a solution.

  • 写回答

2条回答 默认 最新

  • douwu5009 2017-07-28 10:40
    关注

    Maybe not the most elegant solution but got this working by calling relationships and joining as follows:

    $q = ModelOne::with('relation_one', 'relation_two')
        ->with(['relation_three' => function ($q) {
            $q->leftJoin(
                'schema1.model_one',
                'table_three.id',
                '=',
                'model_one.object_id'
            )
            ->where('object', 'Obj1');
        }])
        ->with(['relation_four' => function ($q) {
            $q->leftJoin(
                'schema1.model_one',
                'table_four.id',
                '=',
                'model_one.object_id'
            )
            ->where('object', 'Obj2');
        }])
        ->get();`
    

    If anyone can suggest some improvements or a more efficient way to do this please let me know

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?