gpt4 book ai didi

php - 获取 Eloquent 模型的关系数组

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

我正在尝试获取所有模型关联的数组。我有以下型号:

class Article extends Eloquent 
{
protected $guarded = array();

public static $rules = array();

public function author()
{
return $this->belongsTo('Author');
}

public function category()
{
return $this->belongsTo('Category');
}
}

从这个模型中,我试图得到它的以下关系数组:

array(
'author',
'category'
)

我正在寻找一种方法来自动从模型中拉出这个数组。

我找到了this在 Eloquent 模型上定义关系ToArray 方法,该方法似乎返回模型关系的数组。它似乎使用了 Eloquent 模型的 $this->relations 属性。但是,尽管我的关系设置正确,但此方法返回一个空数组,并且关系属性是一个空数组。

如果不存储模型关系,$this->relations 用于什么?有什么方法可以自动获取模型的关系数组?

最佳答案

这是不可能的,因为只有在使用 with(用于急切加载)或使用模型中定义的关系公共(public)方法(例如,如果 Author 模型是通过以下关系创建的

public function articles() {
return $this->hasMany('Article');
}

当你像这样调用这个方法时:

$author = Author::find(1);
$author->articles; // <-- this will load related article models as a collection

另外,正如我所说的 with,当你使用这样的东西时:

$article = Article::with('author')->get(1);

在这种情况下,第一篇文章(id为1)将加载它的相关模型Author,您可以使用

$article->author->name; // to access the name field from related/loaded author model

因此,如果不使用适当的方法来加载关系,就不可能神奇地获得关系,但是一旦您加载了关系(相关模型),那么您可以使用类似这样的方法来获取关系:

$article = Article::with(['category', 'author'])->first();
$article->getRelations(); // get all the related models
$article->getRelation('author'); // to get only related author model

要将它们转换为 array,您可以使用 toArray() 方法,例如:

dd($article->getRelations()->toArray()); // dump and die as array

relationsToArray() 方法适用于加载了相关模型的模型。该方法将相关模型转换为数组形式,其中toArray()方法将模型(有关系)的所有数据转换为数组,源码如下:

public function toArray()
{
$attributes = $this->attributesToArray();

return array_merge($attributes, $this->relationsToArray());
}

将模型属性及其相关模型的属性转换为数组后合并返回。

关于php - 获取 Eloquent 模型的关系数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21615656/

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