2017-07-28 09:22
浏览 43

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');

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.

图片转代码服务由CSDN问答提供 功能建议


  $  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(  );`

它加载 relation_one relation_two 关系很好,我还需要加载另一种关系 每行, relation_three relation_four ,具体取决于 ModelOne-> object 的值。

我遇到的问题是 ModelOne 来自 schema1 以及 relation_three &中使用的表。 relation_four 来自 schema2

两个模型都设置正确,各自的 protected $ connection protected $ table 变量。

我收到的错误是 relationship_three relationship_four 的表 因子查询检查错误的架构而不存在。

任何人都可以建议如何解决此问题? 浏览过文档,但找不到解决方案。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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) {
            ->where('object', 'Obj1');
        ->with(['relation_four' => function ($q) {
            ->where('object', 'Obj2');

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

    解决 无用
    打赏 举报

相关推荐 更多相似问题