2015-12-25 07:35
浏览 49

Laravel 5.0雄辩的关系问题

I have Tournament, Inside a tournament, I have Categories For each categories, I have CategoriesSettings

I defined a relationship in the Category Model :

 public function settings()
    return $this->hasOne('App\CategorySettings');

So, I can access $tournament->categories without any problem ( with a belongsToMany rel. in Tournament model )

I have 3 tables:

Tournaments, Categories, category_tournament, and CategoriesSettings

category_tournament is just a pivot table.

But when I try to loop on categories, and try to reach settings in the view:

@foreach($categories as $category)
    {{ $category->settings}}

I just get the result for the first category.

Then the result is an array, and I expect a CategorySettings Object.

The funny stuff is when I dd $categories, I have a collection of 6 Categories, but then, when I check the category object, I can't find my hasOne Relationship:

 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

I just find my pivot relation

Here is the query that is ran with :



`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`
`ken_category_tournament` ON `ken_category`.`id` =     `ken_category_tournament`.`category_id`
`ken_category_tournament`.`tournament_id` = ?

and the final query:


select * from `ken_category_settings` 
where `ken_category_settings`.`category_id` = ? 
and `ken_category_settings`.`category_id` is not null limit 1

Can anyone explain me this behaviour ( and how to fix :)???


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

1条回答 默认 最新

  • duanmu8911 2015-12-25 07:51

    Try putting the condition in if statement. If it has settings it will echo out other wise it will keep continue

    @foreach($categories as $category)
      @if(count($category->settings) > 0)
       {{ $category->settings->columnname }}
    解决 无用
    打赏 举报

相关推荐 更多相似问题