多对多关系的新增问题.
有几个多对多关系的表 need, part, need_part
新增后,need_part表中的need_id和part_id都是正常的, 就是没有name。
入库后结果:

以下是代码, 不知道哪里有问题,请大大们帮看~~
有三张表:
need: ( id )
part: (id, name)
need_part: ( id, need_id, part_id, name )
我的三个模型:
Need.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Need extends Model
{
public function parts()
{
return $this->belongsToMany('App\Models\Part');
}
}
Part.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Part extends Model
{
protected $table = 'part';
public function needs()
{
return $this->belongsToMany('App\Models\Need');
}
}
NeedPart.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class NeedPart extends Model
{
protected $table = 'need_part';
public $timestamps = false;
}
控制器中的新增代码:
$parts = Part::whereIn('id', [1,2,3])->get();
$need = Need::find(2);
$need->parts()->saveMany($parts);
推荐文章: