【问题标题】:How to create a relationship within a table in laravel?如何在 laravel 的表中创建关系?
【发布时间】:2020-09-10 06:09:16
【问题描述】:

我需要在表中创建关系。我在下面附上了我的表格。

这是我的类别模型。

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

【问题讨论】:

标签: php laravel e-commerce


【解决方案1】:

你可以试试这个设置:

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 Docs - Eloquent - Relationships - One To ManyhasMany

Laravel 7.x Docs - Eloquent - Relationships - One To Many (Inverse)belongsTo

Laravel 7.x Docs - Eloquent - Relationships - Relationship Methods vs Dynamic Properties

【讨论】:

  • 你能简单解释一下吗? @lagbox
猜你喜欢
  • 1970-01-01
  • 2021-11-10
  • 2016-01-11
  • 2020-07-16
  • 2017-04-13
  • 1970-01-01
  • 2020-04-06
  • 2014-01-22
  • 2013-06-01
相关资源
最近更新 更多