gpt4 book ai didi

php - Eloquent Laravel - 仅当关系存在时才检索结果

转载 作者:可可西里 更新时间:2023-11-01 12:52:10 31 4
gpt4 key购买 nike

我正在尝试检索分配有轨道的流派列表,我正在使用 whereHas Eloquent 查询,但感觉有点迷茫。

我有以下内容

//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
App\Track 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**

朝着正确的方向前进会很棒,我发现这些 Eloquent 东西确实很有用,但我很难理解。

谢谢

最佳答案

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

这样,只有当他们有轨道并且急切加载它们时,您才会获得流派,如果您不想急切加载,请删除 ::with('tracks')

关于php - Eloquent Laravel - 仅当关系存在时才检索结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35410599/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com