2016-01-07 39 views
2

我有兩種模式,書籍和作者。本書屬於關聯作者(我已經削減了部分來自其他地區的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使用生成器/雄辯?我需要使用數據庫查詢嗎?

回答

1

啓用急切加載通過調用('作者')將加載作者在一個單獨的查詢,這就是爲什麼作者的列不可用,並按他們排序不起作用。顯式連接是必需的。

爲了通過你需要與他們的作者加入你的本本的關係進行排序:

Book::select('books.*') 
->join('authors', 'authors.id', '=', 'books.author_id') 
->orderBy('authors.name') 
->get(); 
+0

非常感謝!它只是工作!你甚至可以用()分頁和使用!對於Laravel帶給我的所有挑戰,比如做簡單的數據庫查詢,它有時候會讓我高興。 – whiterook6

0

雄辯回報集合其功能非常強大看到the docs的東西,你可以用

這樣做的命令由作者名字的書,你可以這樣做:

function orderBooksByAutherName($books){ 
    return $books->sortBy(function ($book, $key) { 
       return $book->author->name; 
     }); 
} 

如果你真的想使用加入唯一的選項是使用query builder