laravel在输出时返回整个对象

时间:2017-05-16 10:04:50

标签: php laravel

我遇到了一个问题,我不知道接下来该做什么。所以我正在尝试创建一个类别 - 子类别关系并列出其父项下的所有子类别,它可以工作,但我无法得到子类别的名称,因为我得到了这个

[{"id":2,"name":"dadasda","category_id":2,"created_at":"2017-05-16 09:38:49","updated_at":"2017-05-16 09:38:49"},{"id":2,"name":"djhasjkdhaskjd","category_id":2,"created_at":"2017-05-16 09:56:07","updated_at":"2017-05-16 09:56:07"}]

当我尝试像这样输出它时

@foreach($categories as $category)

    <div class="panel panel-info">
        <div class="panel-heading">{{$category->name}}</div>
    </div>

    <p>{{$category->subcategory}}</p>

@endforeach

但是,例如,我尝试这样做

{{$category->subcategory->name}}

我收到此错误

Property [name] does not exist on this collection instance. (View: /Users/admin/Desktop/LaraProjects/cadilab/resources/views/welcome.blade.php)

我正在使用它来创建关系

public function subcategory()
{
    return $this->hasManyThrough(
        'App\Subcategory', 'App\Category',
        'id', 'category_id', 'id'
    );
}

2 个答案:

答案 0 :(得分:2)

类别模型

public function subcategory()
{
    return $this->hasOne('App\Subcategory', 'category_id', 'id');
}

查看

//if used hasOne
$category->subcategory->name    

//if used hasMany
foreach($category->subcategory as $subcategory) {
    $subcategory->name
}

答案 1 :(得分:0)

查看您提供的集合,您将获得多个记录,这意味着您目前已经设置了每个类别可以有多个子类别。如果这是正确的,那你就错过了一个额外的foreach。

@foreach($categories as $category)

    <div class="panel panel-info">
        <div class="panel-heading">{{$category->name}}</div>
    </div>

    @foreach($category as $subcategory)

    <p>{{$subcategory->name}}</p>

    @endforeach

@endforeach

PS:这可能导致N + 1问题,因此请务必加载关系。 https://laravel.com/docs/5.4/eloquent-relationships#eager-loading