【问题标题】:laravel relationship between 3 tables - many-to-many3个表之间的laravel关系 - 多对多
【发布时间】:2021-08-03 09:43:23
【问题描述】:

我有 3 个表(模型)

Advertise :
    id
    title
    ...

Value:
    id
    title
    amount
    ....

Field:
    id
    name
    title
    ...

and my pivot tables is like:
    advertise_id
    value_id
    field_id

如何在我的模型中设置关系并做一个粗略的处理(请给我一个例子)? 所有的关系都是多对多的

【问题讨论】:

  • 我怎样才能在我的模型中设置关系并做一个 crud(请给我一个例子) 阅读 Laravel docs,它确实在那里!
  • 所有关系都是多对多是什么意思?这是否意味着Advertise多对多FieldAdvertise多对多ValueField多对多Value

标签: php laravel eloquent laravel-8


【解决方案1】:

相应的3个模型类:

class Advertise extends Model
{
    public function fields()
    {
        return $this->belongsToMany(Field::class);
    }

    public function values()
    {
        return $this->belongsToMany(Value::class);
    }
}

class Field extends Model
{
    public function advertises()
    {
        return $this->belongsToMany(Advertise::class);
    }

    public function values()
    {
        return $this->belongsToMany(Value::class);
    }
}

class Value extends Model
{
    public function fields()
    {
        return $this->belongsToMany(Field::class);
    }

    public function advertises()
    {
        return $this->belongsToMany(Advertise::class);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-21
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    • 2014-07-01
    • 1970-01-01
    • 2015-10-11
    • 2021-05-16
    相关资源
    最近更新 更多