user4671628
user4671628

Reputation:

Laravel eloquent One to Many relation

I cannot figure out how to define one to many relation using Eloquent.

Here are tables

----------- Country -----------
id | title | code | currency_code

----------- Currency Code --------
id | name | symbol | code 

One country may have many currencies.

Therefore I defined my models as follows

class Country extends Model
{
    public function currencies()
    {
        $this->hasMany('App\Models\Currency', 'code', 'currency_code');
    }

}

And the Currency model is simple

class Currency extends Model
{


}

And I am selecting countries like that

   return Country::all('country_id AS value', 'title_ru AS title','currency_code')
   ->sortBy('value');

But it returns null when I try to access currencies

What is wrong with my definitions, I would be grateful for any help.

Thanks

Upvotes: 0

Views: 1093

Answers (2)

Roberto Ferro
Roberto Ferro

Reputation: 427

You can set your model like the following code:

Country model:

class Country extends Model
{
    protected $table = 'country';
    protected $primaryKey = 'id';

    public function currency(){
        return $this->hasMany(App\Models\Currency', 'code', 'currency_code');
    }

}

Currency model:

class Currency extends Model
{
    protected $table = 'currency';
    protected $primaryKey = 'id';

    public function country(){
        return $this->belongTo('App\Models\Country', 'code');
    }

}

And then if you wanna get a specific country data (with currency) you can use this:

$data = County::where('id','=',$id)->with('currency')->first();

Or if you wanna get everything you can use:

$data = County::with('currency')->get();

Upvotes: 1

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

You should try this:

Country Model

class Country extends Model
{
    public function currencies()
    {
        $this->belongsTo('App\Models\Currency', 'currency_code');
    }

}

Currency Model

class Currency extends Model
{
    public function country()
    {
        $this->belongsTo('App\Models\Country');
    }

}

Upvotes: 0

Related Questions