sassafras15
sassafras15

Reputation: 43

translating database relationships to Eloquent relationships

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"?

Upvotes: 4

Views: 194

Answers (1)

BrokenBinary
BrokenBinary

Reputation: 7879

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.

Upvotes: 3

Related Questions