【发布时间】: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(),它几乎是一样的。