php - 如何在 laravel 中创建父/子关系?
问题描述
我在 laravel 6.0.4 中有这个模型:
class CategoryModel extends Model
{
public function parent()
{
return $this->belongsTo(CategoryModel::class, 'parent_id');
}
public function children()
{
return $this->hasMany(CategoryModel::class, 'parent_id');
}
}
和控制器
class CategoryController extends Controller
{
public function index()
{
CategoryModel::with('children')->get(); // this is working
CategoryModel::with('parent')->get(); // this is not working
}
}
这是架构
Schema::create('category', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('parent_id')->nullable();
$table->string('name');
$table->index(['parent_id']);
$table
->foreign('parent_id')
->references('id')
->on('category')
->onDelete('set null')
->onUpdate('set null');
});
我可以得到孩子,但对于父母,它为所有记录返回一个空数组。
解决方案
试试这个:
public function parent()
{
return $this->hasOne(CategoryModel::class, 'id', 'parent_id');
}
public function children()
{
return $this->hasMany(CategoryModel::class, 'parent_id', 'id');
}
推荐阅读
- sql - 如何合并两行并使其成为一行 SQL
- sql - 有没有一种惯用的方法来更新 PostgreSQL 中的某些字段?
- javascript - 通过正则表达式验证 js 时得到“太多递归”
- json - 空返回ansible查询
- html - 如何突出显示当前部分 [Power Apps 菜单]
- flutter - 当我滚动屏幕时,复选框在下面的颤动代码中被取消选中?
- laravel - Laravel 仅将 cookie 用于 Nova 后端
- .net - Kubernetes Nginx Ingress TLS 网关到非 TLS 或 mTLS 的上游服务
- python-3.x - 如何将文本放置在多列的按钮中
- r - 如何在进度条上显示实时服务器时间?