【问题标题】:Laravel Eloquent find 1-many with mutatorLaravel Eloquent 用 mutator 找到 1-many
【发布时间】:2014-11-04 00:25:06
【问题描述】:

我试图描绘这个。我有两个模型。

class author extends Eloquent {
    protected $table = 'authors';
    public function getAuthorBioAttribute ($value)
    {
        // when we ask for author::find(1);
        // we will get an author, but we want
        // to mutate the biography of the author
        // based on what the author's book
        // titles are.
    }

    public function books () {
        return $this->hasMany('Book');
    }
}

我要做的是查找所有作者的书籍,然后根据所写书籍的类型更改作者的传记描述。当我们调用这个模型时,通过主 ID 将其拉入,我将得到调整后的生物描述。但是,我不确定如何使用 Eloquent 执行此操作。

books 表包含authors 表的主键的外键。执行此突变的最佳方法是什么?我可以像 $this->books() 这样调用 books 方法并根据外键获取图书数组吗?

编辑:

更多插图。我想做的是这样的:

class author extends Eloquent {
    protected $table = 'authors';
    // Actually an accessor
    public function getAuthorBioAttribute ($value)
    {
        //say $value contains "This string"
        $books = $this->books();
        // $books now has a collection of each book object
        foreach ($books as $book) {

            if ($book->category == 'gardening')
                str_replace($value, "string", $book->category);

        }
    }

    public function books () {
        return $this->hasMany('Book');
    }
}

然后在我的控制器中我想这样使用

public function authorBiography ($id) {

    $author_stuff = author::find($id);

    print_r($author_stuff->authorbio);
    // say that specific author had written some books about gardening
    // Output:
    // "This gardening"
}

【问题讨论】:

  • 不清楚你在问什么,所以显示你需要的示例用法。
  • 添加了插图。我正在尝试使用作者的书籍来更改作者的生物字符串。
  • 然后您可以按照@Marcin 的建议使用访问器(又名获取变异器)。我认为您在这里不需要其他任何东西。
  • 谢谢!雄辩的文档似乎很少,我通读了它们,但没有点击。我只是想想象一下我首先要如何准确地让作者的书与我的访问器一起使用(对我来说,谜团在于foreach ($books...我如何才能得到这些书?
  • 就像@Marcin 的回答 - $this->books 它正在利用动态属性 laravel.com/docs/eloquent#dynamic-properties。否则你可以使用$this->books()->get(),它几乎是一样的。

标签: php laravel eloquent


【解决方案1】:

首先我认为你想创建访问器而不是修改器。您可以在 foreach 循环中访问书籍项目:

public function getAuthorBioAttribute($value)
{       
    foreach ($this->books as $book) {
       echo $book->category;  
    }
    return "something";
}

可能还有其他选项可以执行此操作,具体取决于您的实现和数据库结构。您可以获得作者写得最多的书籍而不是书籍本身(如果没有必要),您还可以在作者表中存储他最常写的书籍类型。

【讨论】:

  • 所以只要有一个public function books () { return $this->hasMany('Book'); }它就会用特定作者的书籍填充一个 $this->books 属性,例如在调用 ::find() 时?
  • @dirtymikeandtheboys books 不是这里的属性,它们是关系,但是在循环中使用时,您将能够获取给定作者的所有书籍数据并使用访问器显示您想要的任何字符串
  • 如果不是属性,那么在你的例子中,是不是更像foreach ($this->books() ...)
猜你喜欢
  • 1970-01-01
  • 2019-04-20
  • 2022-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-21
  • 2020-06-24
相关资源
最近更新 更多