php - 如何在 laravel 的表中创建关系?
问题描述
我需要在表中创建关系。我在下面附上了我的表格。
这是我的类别模型。
class Category extends Model
{
public function products()
{
return $this->hasMany(Product::class);
}
public function categories_id() {
return $this->hasMany('category_id','parent_id');
}
public function parent_id() {
return $this->hasMany('category_id','parent_id');
}
}
在这里我如何关联 category_id 和 parent_id?
这是我的categories_table。
public function up()
{
Schema::create('categories', function (Blueprint $table)
{
$table->bigIncrements('id');
$table->unsignedBigInteger('parent_id')->nullable();
$table->string('cat_name')->nullable();
$table->string('cat_image_path')->nullable();
$table->timestamps();
});
}
解决方案
你可以试试这个设置:
public function parent()
{
return $this->belongsTo(self::class);
// uses `parent_id` to find the parent by 'id'
}
public function children()
{
return $this->hasMany(self::class, 'parent_id');
// finds other records where their 'parent_id' is the parent's 'id'
}
$category = Category::find(...);
$parent = $category->parent;
$children = $category->children;
此外,您的架构中没有category_id
字段。
您想了解的有关这些关系的所有信息都在文档中。
Laravel 7.x 文档 - 雄辩 - 关系 - 一对多 hasMany
Laravel 7.x 文档 - Eloquent - 关系 - 一对多(反向) belongsTo
推荐阅读
- java - java中Enum如何取main方法?
- windows - 有什么方法可以知道 Microsoft Windows 序列号/产品密钥详细信息
- c# - 将excel导入数据库c#asp.net
- scala - 在不使用反向方法的情况下获取列表的最后两个元素?[斯卡拉]
- powershell - 将删除的文件记录到文本文件
- dialogflow-es - Google Dialogflow:获取卡片的 ID
- r - if_else 真值默认为 NA
- c# - 如何使用 HttpWebRequest 在 POST 请求中发送数据
- java - hasPrevious 的检查元素
- javascript - React Form:Form Input 使用时需要 name 属性