sum*_*eto 10 php mysql laravel eloquent laravel-5.1
我有这些表:
条目表
---------------------------------
| id | blog_id | title |
---------------------------------
| 1 | 1 | 1st Entry |
---------------------------------
Run Code Online (Sandbox Code Playgroud)
博客表
-----------------
| id | name |
-----------------
| 1 | 1stBlog |
-----------------
Run Code Online (Sandbox Code Playgroud)
字段组表
-------------------------
| id | blog_id | name |
-------------------------
| 1 | 1 | Group1 |
-------------------------
Run Code Online (Sandbox Code Playgroud)
字段表
---------------------------------
| id | field_group_id | name |
---------------------------------
| 1 | 1 | field_1 |
---------------------------------
Run Code Online (Sandbox Code Playgroud)
值表
------------------------------------------
| id | field_id | entry_id | value |
------------------------------------------
| 1 | 1 | 1 | Hello World |
------------------------------------------
Run Code Online (Sandbox Code Playgroud)
现在在我的模型上我建立了这些关系:
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');
}
}
Run Code Online (Sandbox Code Playgroud)
使用此查询我可以
$entry = Entry::with('blog.field_group.fields')->find(1)
Run Code Online (Sandbox Code Playgroud)
我可以获得该条目,以及其博客,字段组和字段.我想得到与条目相关的值,
$entry = Entry::with('blog.field_group.fields.values')->find(1)
Run Code Online (Sandbox Code Playgroud)
我在使用哪种关系时遇到麻烦.任何帮助深表感谢.我刚开始使用laravel.
我认为你应该将“foreign_key”与“hasMany”和“hasOne”一起使用。
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');
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅 http://laravel.com/docs/4.2/eloquent#one-to-many
| 归档时间: |
|
| 查看次数: |
727 次 |
| 最近记录: |