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条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀