gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-28 23:52:27 24 4
gpt4 key购买 nike

我有这些表:

条目表

---------------------------------
| 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。

最佳答案

试一试......

用 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

关于php - Laravel hasManyThrough 但必须只返回一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32943710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com