我有這些表: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。
嘗試以下http://stackoverflow.com/a/36167391/5704410 –