Laravel get relationship of relationship - laravel

I am trying to retrieve additional data from a relation. But so far I have not been able to do this. It is about a group that contains products. I want to retrieve data related to these products. So far I have not found a solution to realise this.
Tables with fields:
lager_stock_booking_groups
id,datetime
lager_stock_booking
id, lagerProductId, stockBookingGroupId(id from Table lager_stock_booking_groups)
lager_products
id(lagerProductId from Table lager_stock_bookings)
$bookingGroup = LagerStockBookingGroup::with('stockBookingProducts')->where('id', '=', $id)->orderBy('dateTime', 'desc')->get();
This code get me the groups and Products liek this:
Group[ID 23]
Product 1
Product 2
Product 3
I have only the Product-ID's. How can get additional Data of Products from Table lager_products?
Thank you for your help.

you can get with relation :
$bookingGroup->stockBookingProducts
or use join

Related

How Query Multiple dataset in Laravel

I am struggling to get list of places that matches current category(multiple dataset) and city:
what i did is the following,
$cat = Category::find($request->category_id)->toArray();
$cat_id = $cat['id'];
and
$places = DB::table('places')
->where('category',$cat_id)
->where('city_id', $request->city_id)
->get();
See screenshot of the dataset:
Data in the database
For your current problem, you can use the LIKE operator.
$places = DB::table('places')
->where('category','LIKE', '%"'.$cat_id.'"%')
->where('city_id', $request->city_id)
->get();
but the above code will not solve your problem permanently. It looks like you are trying to create a many to many relationship in this case the best practice to use pivot tables for this. Better if you could update the schema as an example and follow the Laravel standards to achieve this. Example:
table: category_place , having columns ["category_id", "place_id"]
in the same way, you need to update the following schema
Place Type
table: place_place_type, columns ["place_id", "place_type_id"]
Amenities
table: amenity_place, columns ["amenity_id", "place_id"]
Ref. link: https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-polymorphic-relations

How to get the record that was inserted by sync

Is there a way to get the record or records that was inserted by sync method?
Something like:
$shop_product = $shop->products()->sync(1);
so I want now $shop_product to be instance that contains the records
{
shop_id: 1,
product_id: 1
}
The sync method updates your products relationship with shop.
So calling $shop->products should return you only products that you synced.
There is no reason to access pivot table data unless you have some additional data there. If you have then you should define in your model relationship that you want it. Like:
return $this->manyToMany(.....)->withPivot(['data_field_name'])
If you are working with shop products you probably don't need pivot table. Usually one product can be related to only one shop so relation will be $this->hasMany(Product::class) and your products table will have shop_id

Eloquent: Using Model::where + with not displaying data

Im trying to create a query using Products Model (refers to Product Table) with Photo Model / Table, Features and locations.
My idea is to filter results of table products in order to display only the information of the current logged user.
This is the query:
$product = Product::where('companyId', '=', Auth::user()->companyId)
->with(['photos','features','locs']);
For some reason I cannot find why when I include
Product::where('companyId', '=', Auth::user()->companyId)
the query stop working.
its possible to use Products:where(condition) + wish?
thanks in advance.
try to use this one ...
Product::where('companyId', Auth::user()->companyId)->get();

show rows with a relation before in Laravel

in a Laravel application, I have a list of companies. Some of those are related to a subscriptions table in a 1 x n relation.
I want to order the companies in a way that the ones which have a subscription appear before the ones which have no subscription using just one db query.
Any idea is much appreciated!
thanks!
Laravel uses separate queries to eager load relationships. So if you want to do this you will need to join the tables and order by...
Something in the form...
$companies = App\Companies::join('subscriptions as sub', 'sub.company_id', '=', 'company.id')
->orderBy('sub.somefield', 'DESC')
->select(what you need)
->with('if you need the relation data');
You know you can also only query those records that have a relationship with
$companies = App\Companies::has('subscription')->get();
Maybe that is all you need... and
$companies = App\Companies::doesntHave('subscription')->get();
... returns the opposite where the company has no subscription...

Laravel Many to Many - 3 models

Some help with many to many relationships in Laravel:
Using the example for roles and users - basically:
a table for all the roles
a table for the users
and table with user_id and role_id.
I want to add to the third table, eg Year. basically the pivot table will have user_id, role_id and year_id.
I want to be able to make a query to pull for example all users assigned a specific role in a specific year. Eg All users with role_id = 2, and year_id = 1.
Any help will be appreciated
Before answering, I would like to suggest you not to put year on database like this.
All your tables should have created_at and updated_at which should be enough for that.
To filter users like you want. You could do this:
// This queries all users that were assigned to 'admin' role within 2013.
User::join('role_users', 'role_users.user_id', '=', 'users.id')
->join('roles', 'roles.id', '=', 'role_users.role_id')
->where('roles.name', '=', 'admin')
->where(DB::raw('YEAR(role_users.created_at)', '=', '2013')
->get();
This example may not be the precise query you are looking for, but should be enough for you to come up with it.
The best way to achieve a three way relation with Eloquent is to create a model for the table representing this relation. Pivot tables is meant to be used for two way relations.
You could have then a table called roles_users_year which could have data related to this 3 way relation like a timestamp or whatever...
A very late answer to a very old question, but Laravel has supported additional intermediate (pivot) table columns of at least Laravel 5.1 judging from the documentation, which hasn't changed at least through Laravel 6.x.
You can describe these extra columns when defining your many-to-many relationship:
return $this->belongsToMany(Role::class)->withPivot('column1', 'column2');
or in your case, the below would also do the job:
return $this->belongsToMany(Role::class)->withTimestamps();
which you can then access via the pivot attribute on your model:
$user = User::find(1);
foreach ($user->roles as $role) {
echo $role->pivot->created_at;
}
Note that the pivot attribute is on the distant relationship model (a single Role) and not on the relationship itself.
To get all the Roles assigned to Users in any given year, you might create a special relationship:
// User.php
public function rolesInYear($year) {
return $this->belongsToMany(Role::class)
->wherePivot('created_at', '>=', Carbon::create($year))
->wherePivot('created_at', '<', Carbon::create($year + 1));
}

Resources