【问题标题】:Laravel hasMany return nullLaravel hasMany 返回 null
【发布时间】: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();

标签: php laravel


【解决方案1】:

验证您的定义

return $this->hasMany('App\Product', 'category_id');

这里有错误,因为附加在类别上,但它会出现在产品上

$table->foreign('category_id')
    ->references('id')->on('products')
    ->onDelete('cascade');

https://laravel.com/docs/5.6/eloquent-relationships#querying-relations

【讨论】:

  • 请在您的回答中添加更多详细信息
  • 他的意思是你应该试试这个类别模型return $this->hasMany(Product::class, category_id);
  • 我的意思是一个类别有很多带有外键 category_Id 的产品,但你的错误是在类别上添加外键
【解决方案2】:

一切正常,只需在产品迁移中进行更改 更改此代码

$table->foreign('category_id')->references('id')
->on('categories')->onDelete('cascade');

$table->foreign('category_id')->references('id')
->on('products'->onDelete('cascade');

【讨论】:

    【解决方案3】:

    请进行以下更改

    1. 更改产品迁移文件(在产品表中)

       $table->integer('category_id')->unsigned();
       $table->foreign('category_id')->references('category_id')->on('categories');
      
    2. 然后更改类别模型

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      • 2023-03-28
      • 2022-06-12
      相关资源
      最近更新 更多