多对多关系的新增问题.

有几个多对多关系的表 need, part, need_part
新增后,need_part表中的need_id和part_id都是正常的, 就是没有name。
入库后结果:
file
以下是代码, 不知道哪里有问题,请大大们帮看~~

有三张表:

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);
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 1

中间表弄个Model干啥?name 字段关联关系不会写数据的,这个逻辑需要你自己实现
用pivot获取中间表内容

7年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!