2015-10-05 27 views
11

我有这些表:Laravel hasManyThrough但必须只返回一个数组

报名表

--------------------------------- 
| 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'); 
    } 
} 

页使用g这个查询我可以

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

我可以得到条目,连同它的博客,字段组和字段。我想获得与该条目相关的值,

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

我遇到了使用哪种关系的问题。任何帮助深表感谢。我刚开始使用laravel。

+0

尝试以下http://stackoverflow.com/a/36167391/5704410 –

回答

0

我认为你应该用'hasMany'和'hasOne'来使用'foreign_key'。

return $ 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

+0

laravel JuniorNune的答案5.1已经为你处理http://laravel.com/docs/5.1/eloquent-relationships#one-to-many – sumpreto

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

相关问题