我安装了Laravel framework 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();
当我在视图中打印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-&gt; 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包中?
答案 0 :(得分:0)
此代码返回对象集合:
$categoryModel->with('category')->get();
但您尝试将其用作对象,这就是您收到错误的原因。
你需要迭代集合以使用它中的对象,所以尝试这样的事情:
@foreach ($categories as $category)
{{ $category->category->name }}
@endforeach