【问题标题】:Eloquent relationships in Laravel 4Laravel 4 中的雄辩关系
【发布时间】:2014-04-10 18:13:25
【问题描述】:

我正在尝试制作一个迷你 CMS 类型的组件,我有三个模型:

Page.php

class Page extends Eloquent {
    protected $table = 'pages';

    public function content() {
        return $this->hasManyThrough('Content', 'PageGroup');
    }

    public function groups() {
        return $this->hasMany('PageGroup');
    }
}

PageGroup.php

class PageGroup extends Eloquent {
    protected $table = 'page_groups'

    public function group() {
        return $this->hasMany("Content");
    }
}

Content.php

class Content extends Eloquent {
    protected $table = 'content';

    public function content() {
        return $this->hasMany("Content");
    }
}

编辑: 我已经用正确的关系建立了我的关系模型。

$page = Page::find(1);
$page_group = $page->groups()->where('id', '=', 1)->get();

返回属于PagePageGroup 集合。我想我的新问题是是否有可能从该集合中获取一个集合...类似于:

$content = $page_group->content;

因为返回:

Undefined property: Illuminate\Database\Eloquent\Collection::$content

这有意义吗?我为新手问题道歉;我刚刚进入 Laravel!

【问题讨论】:

  • 我不确定问题出在哪里 - 您是否收到错误消息?您提供的描述关系的代码中没有任何内容 - 试试laravel.com/docs/eloquent#relationships?这是一个很好的起点。
  • 我的问题是在 Laravel 4 中创建这种关系的最佳方式。如何构建模型?如果这是一个非常低级的问题,我深表歉意。
  • 阅读Kryten给出的链接,你就会知道你上面写的例子调用是行不通的。按照文档中的说明设置关系,如果您有其他问题,请返回。
  • 我用更多细节更新了我的问题。

标签: php orm laravel table-relationships


【解决方案1】:

我觉得自己像个白痴。

方法链$page->groups()->where("id", "=", 1)->get()->content; 将不起作用,因为$page->groups()->where("id", "=", 1); 返回行列表!

$page->groups()->where("id", "=", 1)->first()->content 会起作用。

【讨论】:

  • 是的,使用 Eloquent 可能会更雄辩:$page->groups()->find(1)->content;
猜你喜欢
  • 2015-06-01
  • 1970-01-01
  • 2013-06-04
  • 2014-07-26
  • 2020-09-25
  • 2018-07-24
  • 1970-01-01
  • 2018-11-12
相关资源
最近更新 更多