저는 이것을 그림으로 만들고 있습니다. 두 가지 모델이 있습니다. 내가 할 노력하고있어Laravel Eloquent는 뮤 테이터가있는 1-many를 찾습니다.
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"
}
당신이 묻는 것이 불분명하기 때문에 필요한 예제 사용법을 보여주십시오. –
그림을 추가했습니다. 나는 저자의 약력을 바꾸기 위해 저자의 책을 사용하려고 노력하고있다. – dirtymikeandtheboys
그런 다음 @Marcin이 제안한 것처럼 접근 자 (일명 get mutator)를 사용할 수 있습니다. 나는 네가 여기서 다른 것을 필요로하지 않는다고 생각한다. –