2015-10-05 85 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

相關問題