Laravel在同一模型上的父/子关系 [英] Laravel parent / child relationship on the same model

查看:460
本文介绍了Laravel在同一模型上的父/子关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Category的简单模型,该模型具有以下架构:

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

所需的输出

因此您可以看到我们将获得非常简单的层次结构,如下所示:

The Desired Output

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中映射此关系,以便我可以查询模型并获取其父级(它将始终具有父级)以及子类别(如果存在).

The Issue

I'm trying to map this relationship in Laravel 4.2, so that I can query a model and get its parent (it will always have a parent), and child categories if they exist.

我已经使用以下方法在类别"模型中定义了关系:

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

I can get the parent name working, using

$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)时,它没有输出我期望的结果.

But when I dd($children) it doesn't output what I'd expect.

推荐答案

调用关系函数(->children())将返回关系类的实例.您需要先调用get()或仅使用属性:

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;

进一步的解释

实际上children()children有点不同. children()只是调用您为关系定义的方法.该方法返回HasMany的对象.您可以使用它来应用更多的查询方法.例如:

Further explanation

Actually children() and children are something pretty different. children() just calls the method you defined for your relationship. The method returns an object of HasMany. You can use this to apply further query methods. For example:

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

现在访问属性 children的方法有所不同.您从未定义过它,所以Laravel在后台做了一些魔术.

Now accessing the property children works differently. You never defined it, so Laravel does some magic in the background.

让我们看看Illuminate\Database\Eloquent\Model:

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

当您尝试访问实际上不存在的PHP对象上的属性时,将调用__get函数.

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中首先是一些代码,这些代码检查正常"属性,然后返回.最后,在该方法的最后,如果有定义的关联方法,则调用getRelationshipFromMethod.

Then in getAttribute first is some code that checks for "normal" attributes and returns then. And finally, at the end of the method, if there's a relation method defined getRelationshipFromMethod is called.

然后它将检索关系的结果并将其返回.

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

这篇关于Laravel在同一模型上的父/子关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆