【问题标题】:Problem relationship many to many on LaravelLaravel 上的多对多问题关系
【发布时间】:2019-05-06 08:29:25
【问题描述】:

我是 Laravel 的新手,我遇到了这个问题: 我有 2 个表,platos 和成分,它们具有多对多关系,为此我使用了第三个表,称为成分_platos。

为了保存多对多的关系,我尝试了以下方法:

$platos->ingredientes()->attach($input['ingredientes']);

但它给出了以下错误:

SQLSTATE[23000]:完整性约束违规:1062 键“PRIMARY”的重复条目“151-3”(SQL:插入ingredientes_platosplatos_idingredientes_idnorma_bruta)值(151, 3, ))

看了一下文档,我可以用同步而不是附加来解决,但这并不能解决我的问题,因为除了保存关系的 id 之外,我还需要在数据透视表中保存其他属性。

重要的是要注意,如果我尝试将这些数据保存在 components_platos 以外的表中,我不会遇到这个问题,并且无论我使用哪种方法,数据都会正确保存。

感谢您的关注,希望您能帮助我。

这些是三个表的模型:

表柏拉图:

public $table = 'platos';


protected $dates = ['deleted_at'];


public $fillable = [
    'Grupo',
    'Nombre',
    'Procedimiento',
    'Cantidad',
    'Unidad',
    'Precio'
];

/**
 * The attributes that should be casted to native types.
 *
 * @var array
 */
protected $casts = [
    'Grupo' => 'integer',
    'Nombre' => 'string',
    'Procedimiento' => 'string',
    'Cantidad' => 'integer',
    'Unidad' => 'integer',
    'Precio' => 'double'
];

/**
 * Validation rules
 *
 * @var array
 */
public static $rules = [
    'Grupo' => 'required',
    'Nombre' => 'required'
];

public function ingredientes()
{
    return $this->belongsToMany(Ingredientes::class);
}

public function grupo_platos()
{
    return $this->hasOne('App\Models\Grupo_Platos', 'id', 'Grupo');
}

}

餐桌配料:

public $table = 'ingredientes';

protected $dates = ['deleted_at'];


public $fillable = [
    'Grupo',
    'Nombre',
    'Descripcion',
    'Kcal',
    'Proteinas',
    'Grasas',
    'Unidad',
    'Precio'
];

/**
 * The attributes that should be casted to native types.
 *
 * @var array
 */
protected $casts = [
    'Grupo' => 'integer',
    'Nombre' => 'string',
    'Descripcion' => 'string',
    'Kcal' => 'double',
    'Proteinas' => 'double',
    'Grasas' => 'double',
    'Unidad' => 'integer',
    'Precio' => 'double'
];

/**
 * Validation rules
 *
 * @var array
 */
public static $rules = [
    'Nombre' => 'required'
];

public function platos()
{
    return $this->belongsToMany(Platos::class);
}

}

餐桌配料_柏拉图:

public $table = 'ingredientes_platos';

public $fillable = [
    'platos_id',
    'ingredientes_id',
    'norma_bruta',
    'norma_neta',
    'unidad_id'
];

public $timestamps = false;

}

Platos 控制器:

public function store(CreatePlatosRequest $request)
{
    $input = $request->all();

    $platos = $this->platosRepository->create($input); 
    $id = $platos->id;

    $ingredientes = $input['ingredientes'];
    $norma_b = $input['norma_b'];

    $t = sizeof($ingredientes);

    $i=0;

    for ($i = 0; $i < $t; $i++) { 

        $pivot = new Ingredientes_Platos;

        $pivot->platos_id = $platos['id'];
        $pivot->ingredientes_id = $ingredientes[$i];
        $pivot->norma_bruta = $norma_b[$i];

        $pivot->save();
    }


    Flash::success('Plato agregado correctamente.');

    return redirect(route('platos.index'));
}

【问题讨论】:

    标签: laravel many-to-many relationship


    【解决方案1】:

    如果您需要一种类型多次“属于”另一种类型,反之亦然,那么通用的多对多关系可能不适合您尝试做的事情。不仅因为主键约束,还因为您会遇到为关系返回多行结果的情况,并且多对多关系不知道如何聚合或分组这些。您可能想要提出第三种类型的Model,它类似于“属性”,它与其他两种模型有关系并帮助您实现目标。

    【讨论】:

    • 非常感谢,我的问题已经解决了。碰巧除了 Laravel 之外,我还在使用 InfyOM,当我尝试手动将记录添加到数据透视表时,这会产生冲突,因为这一行已经负责将注册表添加到数据透视表: = $this->dishRepository->create($input);
    【解决方案2】:

    非常感谢,我的问题已经解决了。碰巧除了 Laravel 之外,我还在使用 InfyOM,当我尝试手动将记录添加到数据透视表时,这会产生冲突,因为这一行已经负责将注册表添加到数据透视表: =$this->dishRepository->create($input);

    【讨论】:

      【解决方案3】:
      // Many to Many relationship in category Model to Post model coding here
      namespace App;
      use Illuminate\Database\Eloquent\Model;
      class Category extends Model
      {
              public function posts()
          {
              return $this->belongsToMany('App\Post')->withTimestamps();
          }
      }
      
      // Many to Many relationship in Post Model to Category model coding here
      
      namespace App;
      use Illuminate\Database\Eloquent\Model;
      class Post extends Model
      {
      
          public function categories(){
      return $this->belongsToMany('App\Category')->withTimestamps();
       }
      
      
      
      
      }
      

      【讨论】:

        猜你喜欢
        • 2014-11-11
        • 2015-09-14
        • 2014-05-24
        • 2019-11-25
        • 1970-01-01
        • 2015-04-28
        • 2017-07-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多