Laravel hasManyThrough但必须只返回一个数组

时间:2015-10-05 07:54:25

标签: php mysql laravel eloquent laravel-5.1

我有这些表格:

参赛作品表

---------------------------------
| id  |  blog_id  |     title   |
---------------------------------
| 1   |      1     | 1st Entry  |
---------------------------------

博客表

-----------------
| id  |   name  |
-----------------
|  1  | 1stBlog |
-----------------

字段组表

-------------------------
| id | blog_id |  name  |
-------------------------
| 1  |    1    | Group1 |
-------------------------

字段表

---------------------------------
| id | field_group_id |  name   |
---------------------------------
| 1  |       1        | field_1 |
---------------------------------

价值表

------------------------------------------
| id | field_id | entry_id |    value    |
------------------------------------------
| 1  |    1     |     1    | Hello World |
------------------------------------------

现在,在我的模型上,我建立了这些关系:

class Entry extends Model
{
    public function blog()
    {
        return $this->belongsTo(Blog::class);
    }
}

class Blog extends Model
{
    public function entries()
    {
        return $this->hasMany(Entry::class);
    }

    public field_group()
    {
        return $this->hasOne(FieldGroup::class);
    }
}

class FieldGroup extends Model
{
    public function fields()
    {
        return $this->hasMany(Entry::class);
    }

    public function blog()
    {
        return $this->belongsTo(Blog::class);
    }
}

class Field extends Model
{
    public function group()
    {
        return $this->belongsTo(FieldGroup::class, 'field_group_id');
    }

    public function values()
    {
        // this method should get the values from the Values table per entry id
        return $this->hasManyThrough(Value::class, Entry::class, 'id', 'entry_id');
    }
}

class Value extends Model
{
    public function field()
    {
        return $this->belongsTo(Field::class, 'field_id');
    }
}

使用此查询我可以

$entry = Entry::with('blog.field_group.fields')->find(1)

我可以获得该条目及其博客,字段组和字段。我也希望得到与条目相关的值,

$entry = Entry::with('blog.field_group.fields.values')->find(1)

我无法使用哪种关系。任何帮助深表感谢。我刚开始使用laravel。

2 个答案:

答案 0 :(得分:1)

试试吧......

用field_id替换ID:

return $this->hasManyThrough(Value::class, Entry::class, 'id', 'entry_id');

像这样:

return $this->hasManyThrough(Value::class, Entry::class, 'field_id', 'entry_id');

因为您使用的是标准的laravel列名称,所以可以进一步简化:

return $this->hasManyThrough(Value::class, Entry::class);

见:https://laravel.com/docs/5.1/eloquent-relationships#has-many-through

答案 1 :(得分:0)

我认为你应该将'foreign_key'与'hasMany'和'hasOne'一起使用。

  

返回$ this-> hasMany('Comment','foreign_key');

class Blog extends Model
{
 public function entries()
 {
    return $this->hasMany(Entry::class, 'blog_id');
 }

 public field_group()
 {
    return $this->hasOne(FieldGroup::class, 'blog_id');
 }
}

http://laravel.com/docs/4.2/eloquent#one-to-many