The Setup And Dummy Data

I have a simple model called Category, which has the following schema:

|----------------------------------------------|
| cat_id   | cat_name    | parent_id           |
|----------------------------------------------|
|   1      | Home        |   0                 |
|----------------------------------------------|
|   2      | Products    |   1                 |
|----------------------------------------------| 
|   3      | Services    |   1                 |
|----------------------------------------------|
|   4      | Product A   |   2                 |
|----------------------------------------------|
|   5      | Product B   |   2                 |
|----------------------------------------------|

期望的输出

So you can see that we would get a very straight forward hierarchy as follows:

Home
  - Products
      - Product A
      - Product B
  - Services

这个问题

我试图在Laravel 4.2中映射这种关系,这样我就可以查询一个模型并获取它的父类(它总是有父类)和子类(如果它们存在的话).

I've defined the relationship in the Category model using:

public function children()
{
    return $this->hasMany('Category', 'parent_id', 'cat_id');
}
public function parent()
{
    return $this->belongsTo('Category', 'parent_id');
}

The Problem

我可以使用

$category = Category::findOrFail($id);
return $category->parent->cat_name;

However, I don't understand how to get the child objects.

我试过:

$category = Category::findOrFail($id);
$children = $category->children();

但是当我dd($Children)时,它没有输出我期望的结果.

推荐答案

Calling the relationship function (->children()) will return an instance of the relation class. You either need to call then get() or just use the property:

$children = $category->children()->get();
// or
$children = $category->children;

Further explanation

实际上,children()children是截然不同的东西.children()只调用您为您的关系定义的方法.该方法返回HasMany的对象.您可以使用它来应用进一步的查询方法.例如:

$category->children()->orderBy('firstname')->get();

现在访问property children的工作方式不同了.你从来没有定义过,所以拉威尔在背景中做了一些魔术.

Let's have a look at Illuminate\Database\Eloquent\Model:

public function __get($key)
{
    return $this->getAttribute($key);
}

The __get function is called when you try to access a property on a PHP object that doesn't actually exist.

public function getAttribute($key)
{
    $inAttributes = array_key_exists($key, $this->attributes);

    // If the key references an attribute, we can just go ahead and return the
    // plain attribute value from the model. This allows every attribute to
    // be dynamically accessed through the _get method without accessors.
    if ($inAttributes || $this->hasGetMutator($key))
    {
        return $this->getAttributeValue($key);
    }

    // If the key already exists in the relationships array, it just means the
    // relationship has already been loaded, so we'll just return it out of
    // here because there is no need to query within the relations twice.
    if (array_key_exists($key, $this->relations))
    {
        return $this->relations[$key];
    }

    // If the "attribute" exists as a method on the model, we will just assume
    // it is a relationship and will load and return results from the query
    // and hydrate the relationship's value on the "relationships" array.
    $camelKey = camel_case($key);

    if (method_exists($this, $camelKey))
    {
        return $this->getRelationshipFromMethod($key, $camelKey);
    }
}

然后在getAttribute first中有一些代码判断"normal"属性,然后返回.最后,在方法的末尾,如果有定义的关系,则调用getRelationshipFromMethod方法.

It will then retrieve the result of the relationship and return that.

Laravel相关问答推荐

为什么在Blade 文件中输出用户通知时出现错误?

@vite指令在使用laravel vite构建后导致错误

如何重置laravel ui密码

AJAX响应中未定义的全名

Laravel Eloquent查询与集合优化

Dompdf 古吉拉特语和印地语文本未正确显示

如何传递多个参数给路由

LARVAL SAVE 中的关系有

如何为 CMP 横幅安装谷歌同意脚本?

Laravel Livewire 组件在刷新后不会自动刷新/重新加载

即使上传了文件,Laravel Input::hasFile('image') 也会返回 false

在 Laravel 5 中添加新配置文件不起作用

判断 Laravel 模型表中是否存在列,然后应用条件

PHP Laravel:如何设置或获取会话数据?

Laravel 5.3 auth 判断构造函数返回 false

localhost 和stream_socket_enable_crypto():SSL 操作失败,代码为 1

Laravel League/flysystem 使用 AWS S3 获取文件 URL

Laravel binding绑定的用途和目的是什么?

将参数传递给过滤器 - Laravel 4

如何从 PHPUnit 测试设置运行 Laravel 数据库 seeder 机?