Returning scope data in a collection - laravel

Below is a function I have on a model which brings back a Service with the data from three relationships. The scope closeTo contains data relating to how far a location is from a service which I would also like returned, but it currently only uses it to figure out distances.
return Service::with(['relationship1', 'relationship2', 'locations'])
->whereHas('locations', function ($query) use ($latitude, $longitude, $radius){
$query->closeTo($latitude, $longitude, $radius);
})
->get();
the $query->closeTo uses the function below, and I want to send the distance data back with the return from the first function.
public function scopeCloseTo($query, $latitude, $longitude, $radius = 25)
{
$haversine = "(3959 * acos(cos(radians($latitude))
* cos(radians(latitude))
* cos(radians(longitude)
- radians($longitude))
+ sin(radians($latitude))
* sin(radians(latitude))))";
return $query
->select(['id', 'ccg', 'ccg_code']) //pick the columns you want here.
->selectRaw("{$haversine} AS distance")
->whereRaw("{$haversine} < ?", [$radius]);
}
Whats the best wat to achieve this?

Just add the closeTo statement to your eager loading as a Closure instead of a string:
return Service::with(['relationship1', 'relationship2',
'locations' => function ($query) use ($latitude, $longitude, $radius){
$query->closeTo($latitude, $longitude, $radius);
}])->whereHas('locations', function ($query) use ($latitude, $longitude, $radius){
$query->closeTo($latitude, $longitude, $radius);
})
->get();

Related

Laravel one of many relationship with argument

coming from this relationship from the docs:
https://laravel.com/docs/9.x/eloquent-relationships#advanced-has-one-of-many-relationships
/**
* Get the current pricing for the product.
*/
public function currentPricing()
{
return $this->hasOne(Price::class)->ofMany([
'published_at' => 'max',
'id' => 'max',
], function ($query) {
$query->where('published_at', '<', now());
});
}
how can I make such an relation with a specific date?
The relation down below will work
/**
* Get pricing for the product of one specific date.
*/
public function priceOfDay(Carbon $date)
{
return $this->hasOne(Price::class)->ofMany([
'published_at' => 'max',
'id' => 'max',
], function ($query) {
$query->where('published_at', '<', $date());
});
}
but how can I use it with Eloquent? How can I pass the date to this:
Product::with('priceOfDay')->get();
update
I now use the one to many relation with a closure
->with(['prices' => function ($query) use ($month) {
$query->where('published_at', '<', $month)
->orderByDesc('published_at')
->orderByDesc('id')
->first();
}])
it works with the little drawback of having a collection instead of an object as relation, but it fills my needs for the moment.
It would be nice if there was something like
->with(['relation', $param])
update 2
since there seems to bo no direct solution here the workarround i came up with:
->first() does not work in the query, you will end up getting all prices, so I finished with an each()
->with(['prices' => function ($query) use ($month) {
$query->where('published_at', '<', $month)
->orderByDesc('published_at')
->orderByDesc('id');
}])
->get()
->each(function ($product) {
$product->price = $product->prices->first()->price;
})

Laravel: pass an argument to the relationship function (not the query callback function) when using whereHas

I would like to know how to pass an argument to a model relationship function. Just to be clear, I'm NOT talking about the query callback.
Consider a model like so:
class UserRelationships extends Model
{
// other stuff
// dynamic scope:
/**
* Scope a query to only include users of a given type.
*
* #param \Illuminate\Database\Eloquent\Builder $query
* #param mixed $type
* #return \Illuminate\Database\Eloquent\Builder
*/
// $relationships = UserRelationships::at( Carbon::parse('2022-10-10') )->get();
public function scopeAt($query, Carbon $date)
{
return $query->where('superseded_at', '>', $date )
->where('created_at', '<=', $date );
}
}
And a related model featuring the following relationships:
class User extends Authenticatable
{
public function progenial_relation(Carbon $date=null) // returns this user record in the userRelationships table, which can be used to retrieve this users parent (directly lookup the sponsor_id)
// when eager loading, this is useful for getting all users whose parent is x, hence the name
{
return $this->hasOne(UserRelationships::class, 'user_id', 'id')
->at( #$date ?: Carbon::now() ) // local dynamic scope in userRelationships
->orderByDesc('created_at')
->limit(1);
}
public function parental_relation(Carbon $date=null) // returns records from the userRelationships table, of all the users which refer to this user as their sponsor
// when eager loading, this is useful for getting the user whose child is x, hence the name
{
return $this->hasMany(UserRelationships::class, 'sponsor_id', 'id')
->at( #$date ?: Carbon::now() ); // local dynamic scope in userRelationships
}
}
As you can see my relationships accept an argument (the date).
Now, if you wanted to use those relationships straightforwardly like so, there's no issues:
$date = Carbon\Carbon::parse('2022-06-01');
$relations_at_date = User::find(1)->parental_relation( $date )->get();
But what happens if you need to use eager-loading methods such as has(), whereHas(), doesntHave(), whereDoesntHave()?
How do you pass an argument to the relationship? For example, I wanted to add other relationships to my User model.
public function children(Carbon $date=null)
{
$date = #$date ?: Carbon::now();
return self::whereHas('progenial_relation', function($q) {
$q->where('sponsor_id', $this->id);
}, $date); // not working
}
I tried with these syntax, but it doesn't work:
whereHas( 'relationship_name', $callback, $argument )
whereHas( 'relationship_name', $argument, $callback )
whereHas( 'relationship_name', [$argument], $callback )
whereHas( 'relationship_name', $callback, [$argument] )
Is it somehow possible?
Are there any alternatives?
For completeness I'm going to add what happens if I use a normal closure:
public function children(Carbon $date=null)
{
$date = #$date ?: Carbon::now();
return self::whereHas('progenial_relation', function($q) use ($date) {
$q->at($date)->where('sponsor_id', $this->id);
});
}
This is the resulting SQL. As you can see the constraints are applied twice. Once by the query callback and once by the relationship. But since I cannot pass the correct argument to the relationship, it gets the default one. The 2 constraints collide and the query does not work.
"select * from `users`
where exists (
select *
from `user_relationships`
where `users`.`id` = `user_relationships`.`user_id`
and `user_relationships`.`superseded_at` > ?
and `user_relationships`.`created_at` <= ?
and `sponsor_id` = ?
and `user_relationships`.`superseded_at` > ?
and `user_relationships`.`created_at` <= ?
)
and `users`.`deleted_at` is null"
I don't think that its possible to pass variables to relationship methods when eager-loading like this.
But you can apply a sub-query to the wherehas:
$date = #$date ?: Carbon::now();
return self::whereHas('progenial_relation', function($q) use ($date) {
$q
->where('sponsor_id', $this->id)
->at( #$date ?: Carbon::now() );
}, $date);
Although I'm not sure what the ->at method/scope you added does.

Laravel remove parent if related collection

I have a model with a related collection
now im doing this query
$data = DeliveryPartner::when($filter, function ($q) use ($request) {
})
->with(['orders' => function ($query) {
$query
->where('delivery_partner_invoice_id', '=', '')
->orWhereNull('delivery_partner_invoice_id')
->whereIn('status', ['payment-accepted', 'completed', 'full-refund', 'partial-refund']);
}])->get();
Now i am wondering. If the orders returns empty is it posible to remove this parent from the collection?
I Know i can do this after the eloquent query with a loop. But is it possible to do this in the query?
we cant completely remove that parent ( with index ) BUT you can set those to null using transform() like this;
$data = DeliveryPartner::when($filter, function ($q) use ($request) {
})
->with(['orders' => function ($query) {
$query
->where('delivery_partner_invoice_id', '=', '')
->orWhereNull('delivery_partner_invoice_id')
->whereIn('status', ['payment-accepted', 'completed', 'full-refund', 'partial-refund']);
}])->get()->transform(function($item){
if(!$item->orders->count() ){
return;
}
return $item;
});
Note: this will not completely remove those parents but it will set them to empty.

Callback function of with() returns empty collection

I have three tables: realties, room_types and realty_room_type:
realty_room_type
----------------
id
realty_id
room_type_id
room_type
----------------
id
code
In my Realty model I set a rooms() relationship:
public function rooms()
{
return $this->hasMany(Room::class);
}
I am trying to eager load the rooms() relationship using the with() method. I want to custom what is returned from the relationship, so I am passing a callback function like this:
$realty = Realty::
where('id', $realtyId)
->with([
'rooms' => function ($query) use ($realtyId) {
$query
->leftJoin('room_types', 'room_types.id', '=', 'realty_room_type.room_type_id')
->selectRaw('code, COUNT(*)')
->groupBy('code');
}
])
->get()
);
The problem is I get an empty collection when accessing the relationship using $realty->rooms. Any idea why?
However if I dump and die the statements of the callback function like this:
Realty::
where('id', $realtyId)
->with([
'rooms' => function ($query) use ($realtyId) {
dd($query
->leftJoin('room_types', 'room_types.id', '=', 'realty_room_type.room_type_id')
->selectRaw('code, COUNT(*)')
->groupBy('code'));
}
])
->get()
);
I get what I'd like to be in the rooms() relationship.
Thank you in advance.
You don't need to return inside callback function and call get(). Here you can find the details.
$realty = Realty::
where('id', $realtyId)
->with([
'rooms' => function ($query) use ($realtyId) {
$query
->leftJoin('room_types', 'room_types.id', '=', 'realty_room_type.room_type_id')
->selectRaw('code, COUNT(*)')
->groupBy('code');
}
])
->get();

Querying and filtering on calculated column with eager loading in Eloquent

I currently have three models with a working Eloquent query that uses eager loading. My models have these relationships:
class Template extends Eloquent {
public function user() {
return $this->belongsTo('User');
}
}
class User extends Eloquent implements UserInterface, RemindableInterface {
public function profiles() {
return $this->hasMany('Profile');
}
public function templates() {
return $this->hasMany('Template');
}
}
class Profile extends Eloquent {
public function user() {
return $this->belongsTo('User');
}
}
And my working query looks like this:
$templates = Template::with('user', 'user.profiles')
->where('public', '=', true)
->whereIn('type', $search_types)
->where('user_id', '!=', $user->id)
->paginate(8);
This seems to be working great, but I need to add one more thing to it, which has been very difficult for me to get right. I need to alter this query to take into account the template user's distance from the current user, using the existing lat and long columns in the user table. I only want the query to return the templates whose users are within 25 miles of the current user (ideally ordering by distance, but that part is optional).
I've attempted to add a custom calculated column to the user relationship like so:
$templates = Template::with(array('user' => function($query) use($user) {
$query->select('*')->selectRaw('(3959 * acos(cos(radians(?)) * cos(radians(lat)) * cos(radians(long) - radians(?)) + sin(radians(?)) * sin(radians(lat)))) AS distance', array($user->lat, $user->long, $user->lat));
}, 'user.profiles' => function($query) {
$query
}))
->where('public', '=', true)
->whereIn('type', $search_types)
->where('user_id', '!=', $user->id)
->having('distance', '<=', 25)
->orderBy('distance')
->paginate(8);
This doesn't work because, with the eager loading, the distance column does not exist in the initial query, causing it to fail at the having clause. If I move that part into the anonymous function and remove the ordering, it doesn't immediately fail, but it simply ignores distance for the templates query, and then only grabs the related users who are within 25 miles, which doesn't seem that helpful.
What's the proper way to use Eloquent to get the data I'm after?
I ended up with the following (without the optional ordering), which seems to work well enough:
$templates = Template::with('user', 'user.profiles')
->where('public', '=', true)
->whereIn('type', $search_types)
->where('user_id', '!=', $user->id)
->whereHas('user', function($query) use($user, $distance) {
$query->whereRaw('(3959 * acos(cos(radians(?)) * cos(radians(location_lat)) * cos(radians(location_long) - radians(?)) + sin(radians(?)) * sin(radians(location_lat)))) <= ?', array($user->location_lat, $user->location_long, $user->location_lat, $distance));
})
->paginate(8);

Resources