简体   繁体   English

Laravel 5雄辩的ORM多关系

[英]Laravel 5 Eloquent ORM multi relation

I'm totally new in Laravel, and I'm trying to create relations between models. 我是Laravel的新手,我正在尝试创建模型之间的关系。 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. 我在搞乱用户模型,belongsToMany和hasManyThrough,但是没有运气。

You may need to modify your table structure slightly to make this happen. 您可能需要稍微修改表结构以实现此目的。

I see in your user_area_patch table you are trying to link the user, area, and patches together. 我在user_area_patch表中看到您正在尝试将用户,区域和补丁链接在一起。 That's not typically how I've done it in laravel. 通常,这不是我在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. 如果是这样,则应在补丁表中添加一个user_id。

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. 我对此表示怀疑,因此也要添加一个area_id

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? 这有帮助吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM