Php Laravel有许多返回空值
我有模型类别:Php Laravel有许多返回空值,php,laravel,Php,Laravel,我有模型类别: class Category extends Model { protected $fillable = ['title', 'description', 'keywords', 'slug']; public function getRouteKeyName() { return 'slug'; } public function products() { return $this->ha
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);
}
}
在表products中,我有一个列为category\u id
的产品。但返回null。为什么?我无法使用$category->products
获取当前类别中的产品,因为始终为空。我怎样才能解决这个问题
在型号产品关系类别中
工作,但在型号类别中
不工作
关于桌上产品,我有:
$table->foreign('category_id')
->references('id')->on('categories')
->onDelete('cascade');
验证您的定义
return $this->hasMany('App\Product', 'category_id');
您在这里有错误,因为附加在目录上,但它将在产品上
$table->foreign('category_id')
->references('id')->on('products')
->onDelete('cascade');
一切正常,只需在产品迁移中进行更改即可 更改此代码
$table->foreign('category_id')->references('id')
->on('categories')->onDelete('cascade');
到
请做以下更改
public function products()
{
return $this->hasMany('App\Product','category_id');
}
use App\Category
// include category model where you want to call this function
Category::with('products')->get();
能否显示
类别
表的迁移?能否显示试图访问$category->products
关系的代码?请检查products表中的“category\u id”是否未签名。例如,$table->integer('category_id')->unsigned()代码>请在回答中添加更多详细信息这意味着您应该在类别模型中尝试此选项返回$this->hasMany(产品::类,类别id)代码>我的确切意思是,一个类别有许多带有外键category\u Id的产品,但您的错误在于在类别上添加外键
public function products()
{
return $this->hasMany('App\Product','category_id');
}
use App\Category
// include category model where you want to call this function
Category::with('products')->get();