【问题标题】:Laravel 4 Model Relationship not working properly. Can't access related column from ModelLaravel 4 模型关系无法正常工作。无法从模型访问相关列
【发布时间】:2014-08-21 19:13:24
【问题描述】:

假设我有三个模型:章节、书籍、作者。

A Book hasMany Chapter && Chapter belongsTo Book.

作者有很多书&&书属于作者。

也就是说,ChapterTable 有一个 book_id,而 BookTable 有一个 author_id。

现在我想计算来自特定作者的所有章节。我将如何使用 Blade 来解决这个问题?

这是我的想法:

  $chapters = Book::where('author_id', $author)->with('chapters')->get();
  $chapters = lists('chapter_title');

但这些行无法正常工作,因为章节保存为 book_array 中的数组,我无法按照“lists('chapter_title');”中的建议直接访问章节

当然,一个解决方案是,给每个章节表一个 author_id,然后我就可以这样做:

 $chapters = Chapter::where('author_id', $author)->get();
 $chapters = lists('chapter_title');

我知道这会起作用,但是如果我的章节表上没有作者 ID,是否有可能获得上述结果?

问候,

乔治

【问题讨论】:

    标签: php laravel blade


    【解决方案1】:

    Eloquent 方式使用hasManyThrough:

    // Author model
    public function chapters()
    {
      return $this->hasManyThrough('Chapter', 'Book');
    }
    
    // then
    $author->chapters()->count(); // single query for a single author
    

    为了急切加载多个作者的计数,您需要例如:

    // Author model
    public function chaptersCount()
    {
        return $this->chapters()->selectRaw('count(*) as aggregate')->groupBy('author_id');
    }
    
    public function getChaptersCountAttribute()
    {
        if ( ! array_key_exists('chaptersCount', $this->relations)) $this->load('chaptersCount');
    
        return $this->getRelation('chaptersCount')->first()->aggregate;
    }
    

    然后:

    $authors = Author::with('chaptersCount')->get();
    $authors->first()->chaptersCount;
    
    // or for a single author
    $author->chaptersCount; // load the relation if needed
    

    【讨论】:

      【解决方案2】:

      你可能想看看这个http://laravel.com/docs/eloquent#querying-relations

      $chapters = Book::has('author', $author)->with('chapters')->get();
      $chapters = lists('chapter_title');
      

      对于您的章节,您可以像 Book->chapters 一样访问它们

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-01
        • 2013-12-25
        • 2015-03-22
        • 1970-01-01
        • 1970-01-01
        • 2014-05-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多