【问题标题】:Laravel Eloquent ORM , One to Many , Many to many?Laravel Eloquent ORM,一对多,多对多?
【发布时间】:2018-09-13 09:50:08
【问题描述】:

所以我有这个数据库结构:

页数

id - integer
name - string

id - integer
page_id - integer
name - string

组件

id - integer
row_id - integer
name - string

PAGES 有很多 ROWS,每个 ROWS 有很多 COMPONENTS

我的页面模型有:

public function rows() {
    return $this->hasMany('Models\Rows');
}

我的 Rows 模型有

public function page()
{
    return $this->belongsTo('Models\Page');
}  


public function components() {
    return $this->hasMany('Models\Components');
}

我的组件模型有

public function rows()
{
    return $this->belongsTo('Models\Rows');
}  

所以此刻我有两步方法来获取页面/行中的所有组件。

首先我找到行:

$rows   = PageModel::find(2)->rows;

然后遍历 $rows 并找到组件。

但是这样做不是更有效率吗?

【问题讨论】:

标签: php laravel orm eloquent


【解决方案1】:

你需要一个 hasManyThrough 关系。它对您的情况非常基本。见here

【讨论】:

    猜你喜欢
    • 2013-06-19
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 2013-06-02
    • 1970-01-01
    • 2019-06-18
    相关资源
    最近更新 更多