我有兩種模式,書籍和作者。本書屬於關聯作者(我已經削減了部分來自其他地區的CRUD):您如何通過一對一的關係訂購Laravel Builder?
class Book extends Model {
protected $table = 'books';
protected $fillable = ['title'];
public function author(){
return $this->belongsTo('Author', 'author');
}
}
class Author extends Model {
protected $table = 'authors';
protected $fillable = ['name'];
}
如果我想獲得的所有的書自己的頭銜下令,我會用這樣的:
Books::with(['author'])->orderBy('title', 'asc')->get();
是它可以通過作者的名字訂購這些書籍嗎?我試過很多種組合:
Books::with(['author' => function($query){
$query->orderBy('name', 'asc');
}])->get();
Books::with(['author'])->orderBy('name')->get();
Books::with(['author'])->orderBy('author.name')->get();
Books::with(['author'])->orderBy('authors.name')->get();
但是沒有工作。首先,使用with()查詢命令所有作者,然後再將它們加入到書籍集合中,我想。其他人投擲了500個錯誤。
如果這是普通的MySQL,我會寫這樣的事:
select * from books join authors on books.author_id = authors.id order by authors.name asc;
這是可能的laravel 5.1使用生成器/雄辯?我需要使用數據庫查詢嗎?
非常感謝!它只是工作!你甚至可以用()分頁和使用!對於Laravel帶給我的所有挑戰,比如做簡單的數據庫查詢,它有時候會讓我高興。 – whiterook6