Reputation: 45
I have tables on Database:
orders
--id
--customer_id
customers
--id
--name
--country_id
countries
--id
--name
And next eloquent models:
Order.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function customer()
{
return $this->belongsTo('App\Models\Customer');
}
}
Customer:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function country()
{
return $this->belongsTo('App\Models\Country');
}
}
Country:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
}
Now i need to get all order where customer country name like 'Uk' by one sql query. How I can do it ?
Upvotes: 1
Views: 9012
Reputation: 1
I am not sure if this is a good way of thinking but maybe I have helped
$orders = App\Order::whereHas('customer.country', function ($query) {
$query->where('name', 'like', 'UK%');
})->get();
Upvotes: 0
Reputation: 875
The following should do the trick:
Order::whereHas('customer.country', function($innerQuery) {
$innerQuery->where('countries.name', 'LIKE', 'Uk');
})->get();
Upvotes: 2