【发布时间】:2019-04-17 22:58:04
【问题描述】:
我有模特类别:
class Category extends Model
{
protected $fillable = ['title', 'description', 'keywords', 'slug'];
public function getRouteKeyName()
{
return 'slug';
}
public function products()
{
return $this->hasMany(Product::class);
}
}
并有样板产品:
class Product extends Model
{
protected $guarded = [];
public function category()
{
return $this->belongsTo(Category::class);
}
}
在表格产品中,我有带有 category_id 列的产品。但是返回null。为什么?我无法使用$category->products 获得当前类别的产品,因为总是空的。我该如何解决这个问题?
在模型产品关系category 上工作,但在模型category 上不工作..
我有级联的桌面产品:
$table->foreign('category_id')
->references('id')->on('categories')
->onDelete('cascade');
【问题讨论】:
-
你能显示
category表的迁移吗? -
你能显示你试图访问
$category->products关系的代码吗? -
检查产品表中的“category_id”是否未签名。例如。
$table->integer('category_id')->unsigned();