Reputation: 65
Property Model:
class Property extends Model {
use HasFactory;
protected $table = 'properties';
protected $fillable = ['name', 'address', 'city', 'poskod', 'state', 'facilities'];
/* Get all the units in this property */
public function units()
{
return $this->hasMany(Unit::class);
}
}
Unit Model
class Unit extends Model {
use HasFactory;
protected $fillable = [
'user_id',
'property_id',
'type',
'no',
'owner',
'commission',
'agent',
'availability',
'bed',
'bath',
'sqft',
'rental',
'sale',
];
/* Get the property the unit is in */
public function property() {
return $this->belongsTo(Property::class);
}
}
I need to get all the units which are in a certain city. And city is defined inside a property which is a foreign key to units.
Upvotes: 0
Views: 62
Reputation: 154
I did it by memory, so it is not tested.
$units = Unit::with('property')
->whereHas('property' function ($query) {
$query->where('city', 'Amsterdam');
});
Very good explanation of eager loading and whereHas here: Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?
Upvotes: 1