Laravel 5在belongsTo()关系上返回JSON而不是对象



我已经安装了Laravel框架v5.3.2和dimsav/aravel- translable包v6.0.1。我在同一模型上从belongsTo()关系(父)获取数据时遇到问题。

Category.php

模型
class Category extends Eloquent
{
    public $translatedAttributes = [
        'name', 'slug', 'description'
    ];
    public function category()
    {
        return $this->belongsTo('AppModelCategory', 'category_id', 'id');
    }
    public function categories()
    {
        return $this->hasMany('AppModelCategory', 'category_id', 'id');
    }
}

获取所有类别列表的方法:

$categoryModel = new Category;
$categories = $categoryModel->with('category.translations')->get();

当我在视图中打印name属性时,Laravel抛出异常:"Trying to get property of non-object".

<?php foreach ($categories as $category): ?>
    Name: <?php echo $category->category->name; ?>
<?php endforeach; ?>

但是当我尝试获取value作为数组时,它工作了:

<?php foreach ($categories as $category): ?>
    Name: <?php echo $category->category['name']; ?>
<?php endforeach; ?>

还有一件事,当我尝试var_dump($category->category) inside foreach时,我得到这个:

object(AppModelCategory)[221]...

dd($category) in view inside foreach:

Category {#231 ▼
    #table: "category"
    +translatedAttributes: array:4 [▶]
    +timestamps: false
    #connection: null
    #primaryKey: "id"
    #keyType: "int"
    #perPage: 15
    +incrementing: true
    #attributes: array:3 [▶]
    #original: array:3 [▶]
    #relations: array:2 [▼
        "category" => Category {#220 ▶}
        "translations" => Collection {#228 ▶}
    ]
    #hidden: []
    #visible: []
    #appends: []
    #fillable: []
    #guarded: array:1 [▶]
    #dates: []
    #dateFormat: null
    #casts: []
    #touches: []
    #observables: []
    #with: []
    +exists: true
    +wasRecentlyCreated: false
}

所以对象存在,但Laravel不显示它正确当我尝试直接访问属性。有人知道问题在哪里吗?它是在Laravel中还是在Laravel可翻译的包中?

代码返回对象集合:

$categoryModel->with('category')->get();

但是你试图将它用作对象,这就是为什么你得到错误。

您需要遍历集合以使用其中的对象,所以尝试这样做:

@foreach ($categories as $category)
    {{ $category->category->name }}
@endforeach

最新更新