1

我已经安装了 Laravel 框架 v5.3.2 和dimsav/aravel-translatable包 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();

当我在视图中打印名称属性时,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 包中?

4

1 回答 1

0

此代码返回对象集合:

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

但是您试图将其用作对象,这就是您收到错误的原因。

您需要遍历集合以使用其中的对象,因此请尝试以下操作:

@foreach ($categories as $category)
    {{ $category->category->name }}
@endforeach
于 2016-08-26T07:23:54.113 回答