Reputation: 1677
I'm trying to load all stores from database, with store address and city details.
stores
store_address
cities
I have managed to load all stores with address, but I'm having problems with loading city name by city id.
This is what I'm currently getting:
{
"store_id":1,
"name":"Store Name",
"description":"Store description",
"created_at":"-0001-11-30 00:00:00",
"updated_at":"-0001-11-30 00:00:00",
"address":{
"store_id":1,
"street":"Street name",
"zip":00000,
"city_id":1
}
}
My code:
$stores = Store::with('address')->get();
class Store extends Eloquent
{
protected $table = 'stores';
protected $primaryKey = 'store_id';
public function address(){
return $this->hasOne('StoreAddress', 'store_id');
}
}
class StoreAddress extends Eloquent
{
protected $table = 'store_address';
protected $primaryKey = 'store_id';
}
So I just need to get city name from city table by city_id, I could not find example of this what I'm trying to do.
Thanks.
Upvotes: 0
Views: 529
Reputation: 15372
You should create the belongsTo
city relationship into the StoreAddress
model.
You need something like this:
class StoreAddress extends Eloquent
{
protected $table = 'store_address';
protected $primaryKey = 'store_id';
public function city()
{
return $this->belongsTo('City', 'city_id');
}
}
Ofcourse, you need to create a model for the city (if you have not done it yet).
Upvotes: 4