Php 我想用Laravel Eloquent编写这个SQL—选择属于一本书的所有作者姓名
我想用Laravel雄辩地编写这个SQLPhp 我想用Laravel Eloquent编写这个SQL—选择属于一本书的所有作者姓名,php,laravel,Php,Laravel,我想用Laravel雄辩地编写这个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 有一种更好的方法使用。图书模型应定义以下关系: namespace App; us
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
有一种更好的方法使用。图书模型应定义以下关系:
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');
}
}
如果只想获取作者姓名,可以使用“作者”集合上的方法:
$authors = App\Book::find(1)->authors;
$authorsNames = $authors->reduce(function ($carry, $author) {
$carry[] = $author->name;
return $carry;
}, array());
有一种更好的方法使用。图书模型应定义以下关系:
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');
}
}
如果只想获取作者姓名,可以使用“作者”集合上的方法:
$authors = App\Book::find(1)->authors;
$authorsNames = $authors->reduce(function ($carry, $author) {
$carry[] = $author->name;
return $carry;
}, array());
使用Laravel连接:
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();
试试这个。祝你好运:)使用Laravel连接:
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();
试试这个。祝你好运:)