【发布时间】:2020-11-14 23:31:54
【问题描述】:
我在我的项目中创建了多态关系。当我想像下面这样检索它们时
return view('category.index')->with('categories', Category::all()) ;
它在我 dd() 时返回关系。但是,当我想访问视图中的关系时
当我在视图中调用它时,它会给我以下结果
{"id":1,"image":"abc\/abc.jpg","imageable_id":6,"imageable_type":"App\\Category","created_at":"2020-07-24T13:37:29.000000Z","updated_at":"2020-07-24T13:37:29.000000Z"}
但是当我想访问它说的 id 或图像索引时
试图获取非对象的属性“id”(查看:
D:\WaheedSindhani\Projects\Menu\menu_proj\resources\
视图\类别\index.blade.php)
我不知道这里发生了什么
@if(isset($categories))
@foreach($categories as $category)
<tr>
<th scope="row">{{$loop->index+1}}</th>
<td>{{$category->name}}</td>
<td>{{$category->images->image}}</td>
</tr>
@endforeach
@endif
它说没有找到名为 image 的属性。
迁移如下
图像表
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('image');
$table->unsignedInteger('imageable_id');
$table->string('imageable_type');
$table->timestamps();
});
}
菜单表
public function up()
{
Schema::create('menus', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->boolean('visible');
$table->integer('priority');
$table->timestamps();
});
}
类别表
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->boolean('visibility');
$table->integer('priority');
$table->timestamps();
});
}
型号如下
class Menu extends Model
{
public function images()
{
return $this->morphMany( 'App\Image', 'imageable');
}
}
class Image extends Model
{
protected $guarded = [];
public function imageable(){
return $this->morphTo();
}
}
class Category extends Model
{
protected $guarded = [];
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
}
【问题讨论】:
-
你
but when i want to access the id or image index it says是怎么做到的? -
{{$category->images->id}}