【问题标题】:Laravel 5 Eloquent ORM multi relationLaravel 5 Eloquent ORM 多重关系
【发布时间】:2015-04-16 22:09:01
【问题描述】:

我是 Laravel 的新手,我正在尝试创建模型之间的关系。我的桌子是:

patch
    id
    title

area
    id
    location

area_patch
    id
    patch_id
    area_id

user_area_patch
    id
    area_patch_id
    plant_id
    plant_date

用户模型,“补丁”函数应该像这样执行:

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

我的模型:

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
    }
}

有人可以举个例子吗?我想研究它。我在搞乱用户模型,belongsToMany 和 hasManyThrough,但没有运气。

【问题讨论】:

  • Laravel 5 现在在关系声明中使用命名空间,你忘记了吗?而且,您能否更明确地解释一下(?)您要做什么以及如何做!

标签: php sql laravel orm


【解决方案1】:

您可能需要稍微修改表结构才能实现这一点。

我在您的user_area_patch 表中看到您正在尝试将用户、区域和补丁链接在一起。这通常不是我在 laravel 中所做的。通常您使用pivot table 将两个项目链接在一起。所以让我建议这样的事情:

补丁是否属于单个用户?如果是这样,您应该在补丁表中添加一个 user_id。

patch
    id
    user_id
    area_id
    title

一个补丁可以在多个区域中吗?我有点怀疑,所以我也会添加一个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');
    } 
}

然后您可以开始引用您的补丁,例如:

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

或补丁所属的区域

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

以及一个区域内的所有补丁

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

这有帮助吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 2016-11-19
    • 2015-04-04
    • 2021-05-09
    相关资源
    最近更新 更多