我有比赛, 在锦标赛中,我有分类 对于每个类别,我都有CategoriesSettings
我在分类模型中定义了一个关系:
public function settings()
{
return $this->hasOne('App\CategorySettings');
}
所以,我可以毫无问题地访问$ tournament->类别(在Tournament模型中使用belongsToMany rel。)
我有3张桌子:
锦标赛,类别,category_tournament和CategoriesSettings
category_tournament只是一个数据透视表。
但是,当我尝试循环播放类别并尝试在视图中触及设置时:
@foreach($categories as $category)
{{ $category->settings}}
@endforeach
我只得到第一类的结果。
然后结果是一个数组,我期待一个CategorySettings对象。
有趣的是,当我输入$ categories时,我有6个类别的集合,但是当我检查类别对象时,我无法找到我的hasOne关系:
0 => Category {#437 ▼
#table: "category"
+timestamps: true
#fillable: array:2 [▶]
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
#attributes: array:4 [▶]
#original: array:8 [▶]
#relations: array:1 [▼
"pivot" => Pivot {#436 ▼
#parent: Tournament {#426 ▶}
#foreignKey: "tournament_id"
#otherKey: "category_id"
#guarded: []
#connection: null
#table: "category_tournament"
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:4 [▶]
#original: array:4 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#fillable: []
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
我找到了我的枢轴关系
以下是使用以下命令运行的查询:
$tournament->categories
SELECT
`ken_category`.*,
`ken_category_tournament`.`tournament_id` AS `pivot_tournament_id`,
`ken_category_tournament`.`category_id` AS `pivot_category_id`,
`ken_category_tournament`.`created_at` AS `pivot_created_at`,
`ken_category_tournament`.`updated_at` AS `pivot_updated_at`
FROM
`ken_category`
INNER JOIN
`ken_category_tournament` ON `ken_category`.`id` = `ken_category_tournament`.`category_id`
WHERE
`ken_category_tournament`.`tournament_id` = ?
和最终查询:
$category->settings
select * from `ken_category_settings`
where `ken_category_settings`.`category_id` = ?
and `ken_category_settings`.`category_id` is not null limit 1
任何人都可以解释我这种行为(以及如何修复:) ???
的Tx
答案 0 :(得分:1)
尝试将条件放在if
语句中。如果它有设置,它将以其他方式回应它将继续
@foreach($categories as $category)
@if(count($category->settings) > 0)
{{ $category->settings->columnname }}
@endif
@endforeach