Skip to content
Advertisement

how to compare two separate relations fields with each other in whereHas laravel?

I use laravel 9 and I have 3 model here :

order

city_id
created_at
updated_at

shop

city_id

accepted_order

shop_id
order_id

notice : accepted_order is not pivot table

class order extends Model {
    public function accepted_orders(){
        return $this->HasMany(accepted_order::class);
    }
}

class shop extends Model {
    public function accepted_orders(){
        return $this->HasMany(accepted_order::class);
    }
}

class accepted_order extends Model {
    public function shop(){
        return $this->belongsTo(shop::class);
    }
    public function order(){
        return $this->belongsTo(order::class);
    }
}

Now I want to get accepted_orders where :

order->updated_at < 4 hour ago if order->city_id == shop->city_id

or

order->updated_at < 2 days ago if order->city_id != shop->city_id

and both query orderBy created_at desc.

how can I use whereHas query that compare two separate relations field with each other?

thanks

Advertisement

Answer

I found it

$AcceptedOrders =AcceptedOrders::
        join('shops', 'accepted_orders.shop_id', '=', 'shops.id')
        ->join('orders', 'accepted_orders.cart_id', '=', 'orders.id')
        ->where(function($q){
            $q->where('shops.city_id' ,'<>' ,'orders.city_id')
            ->where('orders.updated_at' , '<' , Carbon::now()->subDays(2)->toDateTimeString());
    })->orWhere(function($q){
            $q->where('shops.city_id' ,'orders.city_id')
            ->where('orders.updated_at' , '<' , Carbon::now()->subHours(4)->toDateTimeString());
    })->paginate(10);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement