多对多关系的新增问题.

有几个多对多关系的表 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);
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 1

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

7年前 评论

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