4
votes

So, I've been trying to watch and read eloquent relationships from laracasts. Unfortunately I still don't quite get how to translate database relationships to eloquent relationships (hasOne, belongsTo, hasMany, etc).

Let's say I have an Account and Customer tables. Account table has a "Customer_id" foreign key which references to the "id" on Customer table. Let's assume it's a one-to-many relationship. How should I put it on my models on laravel?

Which table should contain the "hasMany" and which one should have the "belongsTo"?

1

1 Answers

3
votes

Just think about how you would say it. In your case it sounds like a Customer has many Accounts and an Account belongs to one Customer.

So you would put the hasMany() in your Customer model and the belongsTo() in your Account model.

class Customer extends Model {

    public function accounts() {
        return $this->hasMany('App\Account');
    }

}

class Account extends Model {

    public function customer() {
        return $this->belongsTo('App\Customer');
    }

}

You can read more about Laravel database relationships here.