Arlid
Arlid

Reputation: 99

Laravel blade mixed relationships. How can I do that?

I have a question. I have two tables: devices and persons

In these DB one device can be assigned to one person (so it's one to one relationshiip), but one person may have many devices (so this is one to many relationship).How can I do that in Laravel? For one to one is little easy and in model I can do that:

Devices

class Devices extends Model
{
    public function persons(){

        return $this->hasOne('App\Persons','id');

    }
}

Persons

class Persons extends Model
{
    public function devices(){

        return $this->belongsTo('App\Devices');

    }
}

SO I think this is one to one relationship: one device assigned to one person.

How can I get many device to one person? Change belongsTo to belongsToMany in Persons model? Is these will be allright for those variations?

Upvotes: 4

Views: 149

Answers (2)

Artur Subotkevič
Artur Subotkevič

Reputation: 1939

Try this:

Persons

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

Means that Person will have many Devices.

Devices

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

Means that Device belongs to some Person.


More information: http://laravel.com/docs/5.3/eloquent-relationships#one-to-many

Upvotes: 2

Amit Gupta
Amit Gupta

Reputation: 17658

It's a one-to-many relation, so your relation will look as:

Persons

class Persons extends Model
{
    public function devices(){

        return $this->hasMany('App\Devices');

    }
}

Devices

class Devices extends Model
{
    public function person(){

        return $this->belongsTo('App\Persons');

    }
}

Upvotes: 2

Related Questions