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');
    }
    
  • 3.然后使用产品列表获取所有类别

    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();