I am new to the laravel, i write Eloquent query for fetching the details from the both matching elements from two tables
Books Table
-----
id
name
created_by
OrdersTable
-----------
id
username
updated_at
There is a relation ship between created_by from Books table to Orderstable id , i want to fetch both matching records, can you please help me to achieve this thing
$v=Books::whereNotNull('created_by')->leftJoin('orders',function($join){
$join->on('Books.created_by','=','Orders.id');
})->get();
//created_by column some times null also so that's why i added NoNull condition
CodePudding user response:
I'd suggest you to read the documentation for Laravel Eloquent Relationships.
You can get your data in a single line instead of going around and doing the same work which laravel Eloquent can do in one line.
https://laravel.com/docs/8.x/eloquent-relationships#one-to-many
You can figure out the relationship you want between two models and use it according to documentation.
CodePudding user response:
You have to write their models after that you have to write elaquent function like this :
public function getBooks(){
return $this->hasMany('App\Models\yourOtherModelPath' , 'book_id' , 'id');
}
after this when you wrote query $OrdersTable->getBooks(); you have elequent
