Laravel Eloquent用mutator找到1-many

时间:2014-11-04 00:25:07

标签: php laravel eloquent

我试图想象一下这个。我有两个模特。

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()那样调用书籍方法,并根据外键获取一系列书籍吗?

修改

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

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"
}

1 个答案:

答案 0 :(得分:0)

首先,我认为你想要创建存取器而不是mutator。您可以访问foreach循环中的书籍项目:

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

根据您的实现和数据库结构,可能还有其他选择。你可以获得作者写的最多的书籍而不是书本(如果没有必要),你也可以在作者表中存储他最常写的书。