首页 文章

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

提问于
浏览
1

我安装了Laravel framework v5.3.2和dimsav/aravel-translatable package v6.0.1 . 我在同一模型上从belongsTo()关系(父)获取数据时遇到问题 .

Category.php 型号

class Category extends Eloquent
{
    public $translatedAttributes = [
        'name', 'slug', 'description'
    ];

    public function category()
    {
        return $this->belongsTo('App\Model\Category', 'category_id', 'id');
    }

    public function categories()
    {
        return $this->hasMany('App\Model\Category', 'category_id', 'id');
    }
}

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

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

当我在视图中打印name属性时,Laravel抛出异常:“试图获取非对象的属性” .

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

但是,当我尝试将数值作为数组时,它可以工作:

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

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

object(App\Model\Category)[221]...

在foreach中查看 dd($category) 的结果:

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-translatable包装?

1 回答

  • 0

    此代码返回对象集合:

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

    但是你试图将它用作对象,这就是你得到错误的原因 .

    你需要遍历集合来使用它中的对象,所以尝试这样的事情:

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

相关问题