我看到了大量的相关问题,但似乎无法弄清楚是怎么回事.我使用Laravel 7.x,我有一个分类和产品表.
分类表:
CREATE TABLE categories (
id int(11) unsigned NOT NULL AUTO_INCREMENT,
name varchar(255) DEFAULT '',
PRIMARY KEY (`id`)
)
产品表:
CREATE TABLE products (
id int(11) unsigned NOT NULL AUTO_INCREMENT,
name varchar(255) DEFAULT '',
category_id int(11) unsigned DEFAULT NULL,
PRIMARY KEY (id),
KEY category_id (category_id),
CONSTRAINT products_ibfk_1 FOREIGN KEY (category_id) REFERENCES categories (id) ON DELETE CASCADE ON UPDATE CASCADE
)
在Laravel中我可以做 Product::first()->catgory
然后得到相关类别,用 hasMany
关系的事情似乎变得梨花带雨。
把Category定义成这样。
public function products()
{
return $this->hasMany(Product::class);
}
就会出现错误SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories.category_id' in 'where clause' (SQL: select * from categories where categories.category_id = 1 and categories.category_id is not null)
添加外键和本地键只是返回一个空数组。
Category::find(1)->products;
...
public function products()
{
return $this->hasMany(Product::class, 'id', 'category_id');
}
...
Illuminate\Database\Eloquent\Collection {#306 ▼
#items: []
}
我到底漏了什么?
*编辑。添加上述的FK仍然会出现上述SQL错误。
class Category extends Model
{
public function products()
{
return $this->hasMany(Product::class, 'category_id');
}
}
alt试过...
class Category extends Model
{
public function products()
{
return $this->hasMany(Product::class, 'category_id', 'id');
}
}
试试这个
public function products()
{
return $this->hasMany(Product::class, 'category_id','id');
}
你的问题在于这个关系。
public function products()
{
return $this->hasMany(Product::class, 'id', 'category_id');
}
hasMany的第二个参数是many表中关系的外键...第三个参数代表本地主键...在本例中是Category本地主键...默认情况下应该是'id'当你把category_id写成第三个参数时,laravel在category中寻找category_id这一列,但没有找到...。
在Category模型中的关系应该是:
public function products()
{
return $this->hasMany(Product::class, 'category_id');
}
在Product类中的相反关系应该是::
public function category()
{
return $this->belongsTo(Category::class, 'category_id');
}
更多细节