Laravel查询以使用另一个表和输入从表中获取数据
因此,对于上下文,有3个表。
借款人表
protected $table = 'borrowers';
protected $primaryKey = 'id';
protected $fillable = ['borrower_name', 'IC', 'phone_no', 'address'];
书籍表
protected $primaryKey = 'id';
protected $fillable = ['ISBN', 'year', 'book_title', 'author', 'publisher_name', 'category'];
,最后借用表带有ID,borrower_id,book_id,dessoce_date,return_date,return_date,return_date和late_return_status,这是一个布尔。 borrower_id和book_id是外国钥匙。
用户还执行搜索以选择要显示哪些借款人的借书书。我已经获得了借款人的ID,并将其存储在变量 $ id 中。
因此,我需要查询从借款人借来的书籍表中获取所有信息 + essue_date,return_date和late_return_status。
下面是我到目前为止尝试的。
$books_borrowed = Borrow::join('books', 'borrow.book_id', '=', 'books.id')
->where('borrow.borrower_id', '=', $id)
->get(['books.ISBN', 'books.book_title','books.year' ,'books.author', 'books.publisher_name',
'borrow.issue_date', 'borrow.due_date', 'borrow.late_return_status']);
So for context have 3 tables.
borrowers table
protected $table = 'borrowers';
protected $primaryKey = 'id';
protected $fillable = ['borrower_name', 'IC', 'phone_no', 'address'];
books table
protected $primaryKey = 'id';
protected $fillable = ['ISBN', 'year', 'book_title', 'author', 'publisher_name', 'category'];
and finally borrow table with id, borrower_id, book_id , issue_date, return_date and late_return_status which is a bool. borrower_id and book_id are foreign keys.
The user also performs a search to choose which borrower's borrowed books to show. I've gotten the borrower's ID and stored it in a variable $id.
So i need to query to get all info from books table on books a borrower has borrowed + issue_date, return_date and late_return_status.
Below is what ive tried so far.
$books_borrowed = Borrow::join('books', 'borrow.book_id', '=', 'books.id')
->where('borrow.borrower_id', '=', $id)
->get(['books.ISBN', 'books.book_title','books.year' ,'books.author', 'books.publisher_name',
'borrow.issue_date', 'borrow.due_date', 'borrow.late_return_status']);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信,另一个
JOIN
都缺少boryrers
和books
表链接到外国密钥的表?这样,您就可以加入所有3个表:
I believe that another
join
is missing to get both theborrowers
and thebooks
tables linked to the foreign keys?This way, you have all 3 tables joined: