Reputation: 2963
The scenario is that I have a friend who will only lend me his borrowed books if he knows he can get the same books at another library. So he does the following query:
$collectbook= LibraryOne::where('user_id', Auth::id())->get();
He then needs to loop through the array to collect the relevant IDs predicting that he has 4 books however he is unsure.
if (isset($collectbook)) {
foreach ($collectbook as $books =>$values)
if($books==0){
$first_book = ($values->book_id);
}elseif ($books==1){
$second_book = ($values->book_id);
}elseif($books==2) {
$third_book = ($values->book_id);
}elseif($books==3) {
$fourth_book = ($values->book_id);
}
}
I then runs four separate queries to check if he has the matching books
try {
$collectbookone= LibraryTwo::where('user_id', Auth::id())
->where('item_id', $first_book)->first();
}catch(\Exception $e){
}
try {
$collectbooktwo= LibraryTwo::where('user_id', Auth::id())
->where('item_id', $second_book)->first();
}catch(\Exception $e){
}
try {
$collectbookthree= LibraryTwo::where('user_id', Auth::id())
->where('item_id', $third_book)->first();
}catch(\Exception $e){
}
try{
$collectbookfour= LibraryTwo::where('user_id', Auth::id())
->where('item_id', $fourth_book)->first();
}catch(\Exception $e){
}
The question is whether anyone knows a way of listing all the matching books from library one and library two in a more more elegant way than above. Not knowing how many books one has in the first place is problem..Thanks in advance
Upvotes: 0
Views: 44
Reputation: 855
You should use sql joins. Based on the functions you are using laravel. You have model LibraryOne and LibraryTwo. Assuming the actual table name for LibraryOne is libraryOne and LibraryTwo is libraryTwo, your code should look like this:
DB::table('libraryOne')->where('libraryOne.user_id', Auth::id())->join('libraryTwo', function($join)
{
$join->on('libraryOne.book_id', '=', 'libraryTwo.item_id')->where('libraryTwo.user_id', Auth::id());
})
->get();
This would list all the books that are both on libraryOne and libraryTwo. Im just curious why the book identifier on libraryOne is book_id while on libraryTwo it is item_id. Piece of advice, learn read about sql joins. You will need that knowledge moving forward in your career.
Upvotes: 1