Reputation: 100
I have got this relationships:
CUSTOMER
id
name
ADDRESS
id
name
customer_id
country_id
COUNTRY
id
name
My Customer model:
class Customer extends Model
{
use SoftDeletes;
public function addresses()
{
return $this->hasMany(Address::class);
}
My address model:
class Address extends Model
{
use SoftDeletes;
public function country()
{
return $this->hasOne(Country::class);
}
And right now doing:
Customer::with('addresses')->orderBy('id', 'DESC')
I can get all customer with his addresses. But How Can I get the name of country fro customer?
I know getting in blade, if I do 2 loops I can create $address variable and get country names:
loop customers
loop adddresses
$address->name
$address->country (name of country)
But if I try in Vue:
<tr v-for="(customer, index) in customers" :key="customer.id">
<td>{{ customer.id}}</td>
<td>{{ customer.firstname}}</td>
<td>{{ customer.lastname}}</td>
<td v-if="customer.addresses">
<tr v-for="(address, index) in customer.addresses" :key="address.id">
<td>{{ address.name }}</td>
<td>{{ address.country }}</td>
</tr>
</td>
I dont get any value in addres.country. I mean, how Can I relate CUSTOMERS & COUNTRIES for usign in Vuejs?
Thans in advance
Upvotes: 0
Views: 291
Reputation: 100
I found a solution!
I updated Address model like this:
class Address extends Model
{
public function country()
{
return $this->belongsTo(Country::class);
}
protected $with = ['country'];
}
then I can solve country name like this:
<tr v-for="(customer, index) in customers" :key="customer.id">
<td>{{ customer.id}}</td>
<td>{{ customer.name}}</td>
<td v-if="customer.addresses">
<tr v-for="(address, index) in customer.addresses" :key="address.id">
<td>{{ address.name }}</td>
<td>{{ address.country.name }}</td>
</tr>
</td>
Upvotes: 1