Luke
Luke

Reputation: 183

Laravel 5 Eloquent ORM multi relation

I'm totally new in Laravel, and I'm trying to create relations between models. My tables are:

patch
    id
    title

area
    id
    location

area_patch
    id
    patch_id
    area_id

user_area_patch
    id
    area_patch_id
    plant_id
    plant_date

User model, "patchs" function should execute something like this:

SELECT
    p.id, p.title, up.plant_id, up.plant_date
FROM
    rsst_farming_patch p
JOIN rsst_farming_area_patch pp, 
    rsst_farming_user_patch up ON pp.id = up.area_patch_id AND p.id = pp.patch_id WHERE up.user_id = 1

my models:

class User extends Model {
    public function patchs() {
        //return user patchs
    }
}
class Patch extends Model {
     public function area() {
         //return area that this patch belongs to
     }
}
class Area extends Model {
    public function patchs() {
         //return available patchs
    }
}

can some one make an example of this? I would like to study it. I was messing around with User model, belongsToMany and hasManyThrough, but no luck.

Upvotes: 1

Views: 639

Answers (1)

Jesse Schutt
Jesse Schutt

Reputation: 396

You may need to modify your table structure slightly to make this happen.

I see in youruser_area_patch table you are trying to link the user, area, and patches together. That's not typically how I've done it in laravel. Normally you use a pivot table to link two items together. So let me suggest something like this:

Does a patch belong to a single user? If so you should add a user_id to the patch table.

patch
    id
    user_id
    area_id
    title

Can an a Patch be in multiple areas? I kind of doubt it, so I'd add an area_id as well.

class User extends Model {
    public function patchs() {
        return $this->hasMany('App/Patch', 'user_id');
    }
}
class Patch extends Model {
    public function area() {
         return $this->belongsTo('App\Area', 'area_id');
    }
}
class Area extends Model {
    public function patchs() {
         return $this->hasMany('App\Patch', 'patch_id');
    } 
}

Then you can start referencing your patchs like:

$patchs = User::find(1)->patchs()

or the area that a patch belongs to by

Patch::find(1)->area()

and all the patchs in an area by

Area::find(1)->patchs()

Does this help?

Upvotes: 1

Related Questions