How to make left join in many to many relationship laravel - laravel

I am new in laravel. I have 3 tables
users
ingredients
user_ingredients(pivot table)
Now i have established many-to-many relationship but I have a special requirement that I want to get matching records(which is done) with all the ingredients in ingredients table. I can do it using query_builder or raw but I want to do it in eloquent.
I have searched about 4 hours to find any solution in eloquent but did not found.
Here is my code
User Model
public function ingredients()
{
return $this->belongsToMany('App\Ingredient', 'user_ingredients');
}
Ingredient Model
public function user()
{
return $this->belongsToMany('App\User', 'user_ingredients');
}
Controller Code
$ingredients = $user->ingredients()->get();
Query Builder query
select ingredients.*,user_ingredients.liked from ingredients LEFT JOIN user_ingredients on ingredients.id = user_ingredients.ingredient_id and user_ingredients.user_id=129
I have checked has(),with() but nothing according to my requirement.
Please help me. Thanks

If I understand your question correctly, you are just trying to access all the ingredients on the user model? In that case, you should be able to just do $user->ingredients
You can access the relationship as a property on the user object. It's some behind the scenes Laravel magic that handles this.

Related

Nested eloquent relationship

I just started my first laravel project today and stumbled upon this confusing situation,
I intended to use eloquent relationship instead of manually joining tables on query. So here it goes...
I have 3 tables which are users , tbl_instruments_taught , tbl_instruments
users table does not hold any of the table's ID,
tbl_instruments_taught - holds the id of user and intruments
Note: user can teach multiple instruments
Now, I implemented a hasOne on my other result set but I dont think hasOne works on this one. I read about belongsToMany but as I try implement it, it seems like every minute, it gets confusing.
Any idea?
I think you are looking for pivot table and relation many to many.
You have users table, instruments table (user has many instruments and one instrument could belong to many users) and user_instruments pivot table. Here db model:
And then add belongsToMany relationship in User and Instrument model (with specified pivot table). Like so:
//IN USER MODEL
public function instruments()
{
return $this->belongsToMany('App\Models\Instruments', 'users_instruments', 'user_id', 'instrument_id');
}
//IN INSTRUMENT MODEL
public function users()
{
return $this->belongsToMany('App\Models\Users', 'users_instruments', 'insrument_id', 'user_id');
}
Now you can reach instruments/users data through laravel relations/eager loading.

How to search for all associations in a relationship tree in Laravel?

I'm having a problem. I have tables that relate:
internal_clients->subsidiaries->departments->job_titles->users
I also have their respective models.
My doubt is:
How do I get all the data associated with users from the top of the tree (internal_clients)
?
I'm trying to follow the Laravel documentation using hasManyThrough.
However, in the documentation it explains only how to do it in a chain of three tables. They teach how to place an intermediate table (model) as the second parameter of the hasManyThrough method (BaseClasse::class, IntermediaryClass::class).
However, in my case that has several tables between users and internal_clients, how would I do this? What would be the intermediate table?
I would like to make a query that returns the user's internal_client, subsidiary, department and jobTitle (associated with users).
I'm trying to do it this way:
Model InternalClient
public function users()
{
return $this->hasManyThrough(User::class, InternalClient::class);
}
Controller UserController
public function allRelations($internalClientId)
{
$internalClient = InternalClient::find($internalClientId);
$users = $internalClient->users;
return response()->json($users, 201);
}
The InternalClient id arrives at the controller above.
When I access the route, the error below is returned:
In short: I would like to know if there is a way to get all the data (from all tables that are in this hierarchical tree) that are associated with the User.
I couldn't find an answer on the Stackoverflow PT-BR.
Thank you!

How to get the full Relation in Laravel/Eloquent

at the moment i try to learning Laravel and Laravel Eloquent.
I try to solve a problem using relations in Laravel.
I have following Database Structure in my simple Laravel Project.
table players:
id name
table clubs:
id name icon
table players_x_clubs:
player_id club_id
it's a one to many Relation.
Is it possible to get the full club Object who is combined with the player_id?!
The first try was to add this to my Player Model
public function club()
{
return $this->hasOne('App\PlayersXClub');
}
Here, i only get the PlayersXClub Relation with the player_id and the club_id
but i want to get the full club object from the club table, is it possible in a simple way?
any ideas how i have to realize is it correctly?
my solution was this:
public function getClubRelation()
{
$clubRelation = $this->hasOne('App\PlayersXClub')->get()->first();
$club = Club::whereId($clubRelation->club_id)->get()->first();
return $club;
}
With this solution i can do this in my code $player->getClubRelation()->icon
but i don't know if its correct solved or is there a more simple way to resolve it with Eloquent?
You always have access to objects relations. For example:
$player = Player::find(1);
$club = $player->club;
or better
$player = Player::with('club')->find(1);
However, I believe you don't need an additional table. An additional table would result in a many to many relation which doesn't make much sense here.
A player belongs to a single club and a club can have many players. So it's one to many.
You should add a club_id foreign key to players table.
$table->unsignedBigInteger('club_id');
$table->foreign('club_id')->references('id')->on('clubs')->onDelete('cascade');
Player Class
public function club() {
return $this->belongsTo(Club::class);
}
Club Class
public function players() {
return $this->hasMany(Player::class);
}

Laravel pivot relationship on relationship (Eloquent)

In Laravel, is it possible to put a relationship within a relationship?
Basically, I already have a relationship set up, but I then need another relationship for that relationship (if that makes sense).
My two models:
Store
Supplier
My relationship model for Store and Supplier:
SupplierStore
store_id
supplier_id
As you can see, I have many stores and suppliers, each of whom can relate to each other through the SupplierStore table.
This works perfectly.
My problem is that for each relationship (of Store and Supplier) there can be
many Delivery Days.
My HasMany relationship:
DeliveryDay
supplier_store_id
day
I thought if I go into the SupplierStore model and add:
public function days()
{
return $this->hasMany('App\DeliveryDay');
}
Would work, but there is no way I can seem to access this data through eloquent?
I was hoping to do something like this:
$supplier = Supplier::find($id);
$supplier->store->pivot->days
The pivot (SupplierStore) would hold the relationship of that specific relation and I could grab the days.
Can anyone help me figure out what I need to do to achieve this? Your time is much appreciated. After googling for hours, my head hurts so much. :)
You could access each day like this:
public function getDays($id)
{
$supplier = Supllier::find($id);
foreach($supplier->stores() as $store)
{
foreach($store->days() as $day)
{
echo $day->day;
}
}
}
Or get all days
$supplier->stores->days;

How to retrieve data through model?

I have Order model with another relation OrderPhoto:
public function OrderPhoto()
{
return $this->hasMany('App\OrderPhoto');
}
In turn OrderPhoto model has relation:
public function Photo()
{
return $this->belongsToMany('App\Photo');
}
So, how to get data from OrderModel with related data from third model Photo?
I guess this:
Order::with("OrderPhoto.Photo")->get();
to retrieve only data from Photo model for each Order
So, each Order has some OrderPhotos. Relationship is one to many.
But one item from OrderPhotos is related with primary key from table Photos. It is one to one relation.
My result query should be:
select `photos`.*, `ordersphoto`.`Orders_Id` from `photos` inner join `ordersphoto` on `ordersphoto`.`Photos_Id` = `photos`.`Id` where `ordersphoto`.`Orders_Id` in (1);
How to use hasManyThrough for this query?
Just having a quick look at your relationships it looks like you could create a hasManyThrough relationship on the order Model.
public function Photo {
return $this->hasManyThrough('App\OrderPhoto', 'App\Photo')
}
You may need to add the table keys to make it work
This will allow you to do:
Order::with("Photo")->get();
You can see more details here https://laravel.com/docs/5.5/eloquent-relationships#has-many-through
Update
Try this
public function Photo {
return $this->hasManyThrough('App\Photo', 'App\OrderPhoto', 'Order_id', 'Photos_id', 'id', 'id')
}
It is a little hard to get my head around your DB structure with this info but you should hopefully be able to work it out. This may also help
https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Concerns/HasRelationships.html#method_hasManyThrough

Resources