Вопрос

In Laravel i'm trying to make output, relational data with Model using hasOne.

My tables are:

User
--------
id name  country_id    
1  Hakan   1

Country
--------
id country
1   Turkey

My Model is given below:

class User extends Eloquent{

public function country() {
        return $this->hasOne('Country','id','country');
    }

}

view code:

$country = User::find(1)->country;

When I run this code, it outputs id of country but I want to echo Country Name. I tried and searched but couldn't find any help.

Это было полезно?

Решение

According to your table relation below

User
--------
id name  country_id    
1  Hakan   1

Country
--------
id country
1   Turkey

Your relation in the model should be

class User extends Eloquent{
    public function country() {
        return $this->belongsTo('Country');
    }
}

So you can get country name using

$country = User::find(1)->country;
echo $country->country;

If you want to use something like this

$users = Country::find(1)->users;
echo $users->first()->name; // get the first user's name
echo $users->get(1)->name; // get the second user's name

Then you may use hasMany in your Country model like

class Country extends Eloquent {
    public function users()
    {
        return $this->hasMany('User');
    }
}

Другие советы

When you run $country = User::find(1)->country;, $country will now hold an instance of your Country model. If you want to access the country name, you'll need to get it via a property of said model:

echo $country->country;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top