class Product extends Model
{
use HasFactory;
protected $fillable = [
'productName',
'quantity',
'weight',
'boxes',
'MRP',
'costprice',
'productDescription',
'seller_id',
'category_id'
];
public function image()
{
return $this->morphOne(Image::class,'imageable');
}
}
class Image extends Model
{
use HasFactory;
protected $fillable = [
'url',
'size',
'filename',
'imageable_id',
'imageable_type',
];
public function imageable()
{
return $this->morphTo();
}
}
class ProductController extends Controller
{
function index()
{
$product = Product::with('image')->get();
return view('layouts.ecommerce.productAvailable', compact('product'));
}
}
<!---------productAvailable.blade.php--------------
@foreach($product as $key => $val)
<td>{{ $val['image']['id'] }}</td>
@endforeach
我无法遍历关系,但是当我使用 $val['image'] 它返回一个集合
@foreach($product as $key => $val)
<td>{{ $val['image'] }}</td>
@endforeach
{"id":3,"imageable_id":14,"imageable_type":"App\\Models\\Product","url":"images\/j1zRX7Cs1DaWFWc1hIi9c17A7Pzj9G7tUMdj576q.jpg","size":"51313","filename":"1643628568.blacky.jpg","created_at":"2022-01-31T11:29:29.000000Z","updated_at":"2022-01-31T11:29:29.000000Z"}
{"id":4,"imageable_id":24,"imageable_type":"App\\Models\\Product","url":"images\/Dz05JmPPuGFSFOO2U1gcb2LJHAz7H63BLGZtPWdQ.jpg","size":"281910","filename":"1643629631.starlet.jpg","created_at":"2022-01-31T11:47:11.000000Z","updated_at":"2022-01-31T11:47:11.000000Z"}
{"id":5,"imageable_id":26,"imageable_type":"App\\Models\\Product","url":"images\/vDdYJKfhy3vzHnfJmxBWA7H8qY1M6Ph9ccfBmc0X.jpg","size":"80911","filename":"1643629652.chuhiya3.jpg","created_at":"2022-01-31T11:47:32.000000Z","updated_at":"2022-01-31T11:47:32.000000Z"}