加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – Eloquent Laravel – 仅在关系存在时检索结果

发布时间:2020-12-14 19:56:06 所属栏目:大数据 来源:网络整理
导读:我正在尝试检索已分配给它们的轨道的类型列表,我正在使用whereHas雄辩的查询但感觉有点迷失. 我有以下内容 //modelpublic function workingGenre() { $this-whereHas('tracks',function($query) { $query-where(''); }); return $this-tracks()-first();}//c
我正在尝试检索已分配给它们的轨道的类型列表,我正在使用whereHas雄辩的查询但感觉有点迷失.

我有以下内容

//model
public function workingGenre() {
    $this->whereHas('tracks',function($query) {
        $query->where('');
    });

    return $this->tracks()->first();
}

//controller (where i am passing variables etc)
$genres = Genre::with('tracks')->get();

//my view
@foreach($genres as $genre)
   {{print_r($genre->workingGenre())}}
@endforeach

我知道我的Where是空的,目前我的print_r返回以下内容:

1
                                        AppTrack Object
 (
[table:protected] => Track
[fillable:protected] => Array
    (
        [0] => id
        [1] => GenreId
        [2] => Title
        [3] => CreatedById
        [4] => SelectedCount
        [5] => ProducerName
        [6] => SourceId
        [7] => Published
    )

[connection:protected] => 
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
    (
        [id] => 6
        [GenreId] => 4
        [Title] => Guns Up
        [CreatedById] => 1
        [SelectedCount] => 0
        [ProducerName] => 
        [SourceId] => 1
        [Published] => 1
    )

[original:protected] => Array
    (
        [id] => 6
        [GenreId] => 4
        [Title] => Guns Up
        [CreatedById] => 1
        [SelectedCount] => 0
        [ProducerName] => 
        [SourceId] => 1
        [Published] => 1
    )

[relations:protected] => Array
    (
    )

[hidden:protected] => Array
    (
    )

[visible:protected] => Array
    (
    )

[appends:protected] => Array
    (
    )

[guarded:protected] => Array
    (
        [0] => *
    )

[dates:protected] => Array
    (
    )

[dateFormat:protected] => 
[casts:protected] => Array
    (
    )

[touches:protected] => Array
    (
    )

[observables:protected] => Array
    (
    )

[with:protected] => Array
    (
    )

[morphClass:protected] => 
[exists] => 1
[wasRecentlyCreated] => 
)

**And so on**

向正确的方向推进会很棒,我发现这整个雄辩的东西真的很有用,但很难绕过我的脑袋.

谢谢

$genres = Genre::with('tracks')->has('tracks')->get();
    foreach($genres as $genre)
       //do what you need
    endforeach

这样你就可以获得Genre,只要他们有曲目和渴望加载它们,如果你不想急切加载remove :: with(‘tracks’)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读