我想在Laravel Eloquent 中编写这个SQL
SELECT book.book_id,book.book_name,author.author_name,book.price,book.publication
FROM author,book,book_author
WHERE bookauthor.b_id=book.book_id and bookauthor.a_id=author.author_id
使用雄辩的关系有更好的方法。Book模型应该定义以下关系:
namespace App;
use Illuminate'Database'Eloquent'Model;
class Book extends Model
{
/**
* Get the authors for the book.
*/
public function authors()
{
return $this->hasMany('App'Author');
}
}
作者应该属于这本书:
namespace App;
use Illuminate'Database'Eloquent'Model;
class Author extends Model
{
/**
* Get the book of the author.
*/
public function book()
{
return $this->belongsTo('App'Book');
}
}
如果你只想获得作者的名字,你可以在作者集合上使用reduce方法:
$authors = App'Book::find(1)->authors;
$authorsNames = $authors->reduce(function ($carry, $author) {
$carry[] = $author->name;
return $carry;
}, array());
使用Laravel Joins:
bookauthor::Join('book', 'book.book_id', '=', 'bookauthor.b')
->Join('author','bookauthor.a_id','=','author.author_id')
->select('book.book_id','book.book_name','author.author_name','book.price','book.publication')
->get();
试试这个。祝你好运:)