简体   繁体   English

Laravel 5.3-HasMany Relationship不适用于Join语句

[英]Laravel 5.3 - HasMany Relationship not working with Join statement

I am trying to retrieve symbols with their comments using hasMany in laravel 5.3 我试图在Laravel 5.3中使用hasMany检索带有注释的符号

Symbol.php Symbol.php

public function comments() {
    return $this->hasMany('App\Comment');
}

Comment.php Comment.php

public function symbol() {
    return $this->belongsTo('App\Symbol');
}

when I run: 当我跑步时:

$symbols = Symbol::with('comments')->paginate(100);

I get the correct output (lists all symbols with their comments) 我得到正确的输出(列出所有符号及其注释)

@foreach ($symbols as $s)
    {{ $s->name }}
    @foreach ($s->comments as $c)
         {{ $c->body }}
    @endforeach
@endforeach

but when I add a join to the statement: 但是当我在语句中添加联接时:

$symbols = Symbol::with('comments')
    ->join('ranks', 'symbols.id', '=', 'ranks.symbol_id')
    ->join('prices', 'symbols.id', '=', 'prices.symbol_id')
    ->paginate(100);

The foreach loop has no comments for every symbol. foreach循环没有对每个符号的注释。 Any idea why the join would be causing this? 知道为什么联接会导致这种情况吗?

When you are doing joins like this, attributes with the same names will be overwritten if not selected. 当您进行这样的联接时,如果未选择,则具有相同名称的属性将被覆盖。 So select the attributes you need for your code, and nothing else. 因此,选择您的代码所需的属性,别无其他。 As shown below. 如下所示。

$symbols = Symbol::with('comments')
    ->join('ranks', 'symbols.id', '=', 'ranks.symbol_id')
    ->join('prices', 'symbols.id', '=', 'prices.symbol_id')
    ->select('symbols.*', 'ranks.importantAttribute', 'prices.importantAttribute')
    ->paginate(100);

Basicly i think your ids are being overwritten, by the two joins because they also have id fields, i have had a similar problem doing joins, and it breaks relations if the id is overwritten. 基本上,我认为您的id被两个联接所覆盖,因为它们也具有id字段,我在进行联接时遇到了类似的问题,如果id被覆盖,则会破坏关系。

And you have to be carefull, all fields who shares names can be overwritten and parsed wrong into the models. 而且,您必须小心,所有共享名称的字段都可能被覆盖并错误地解析到模型中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM