1. 关联写入
      1. 新增有三种方式,我们一一来看,比如给一个用户增加关联书籍:

    //先限定用户
    $user = User::find(20);
    //给这个用户关联的book 新增一条记录
    //user_id会自动写入19,title自定义
    $user->book()->save(new Book([‘title’ => ‘《哈利波特》’, ‘id’=>’8’, ‘user_id’=>’20’]));
    PS: 一定要先去那个对应添加的模型里添加protected $guarded = []; (批量赋值取消),public $timestamps = false; (取消自动时间字段)
    b. 需要设置批量赋值,我们取消掉,book表没有时间字段,也要取消自动写入
    //取消批量赋值
    protected $guarded = [];
    //取消自动时间字段
    public $timestamps = false;

    //批量新增
    $user = User::find(20);
    $user->book()->saveMany([
    new Book([‘title’ => ‘《鼠疫》’, ‘id’=>’9’, ‘user_id’=>’20’]),
    new Book([‘title’ => ‘《华为》’, ‘id’=>’10’, ‘user_id’=>’20’]),
    ]);
    c. create和createMany 只需要插入数组即可完成关联新增;
    $user->book()->create([
    ‘id’ => ‘11’,
    ‘user_id’ => ‘20’,
    ‘title’ => ‘《哈利波特》’,
    ]);
    //createMany创建多个
    $user->book()->createMany([
    [‘id’ => ‘12’,
    ‘user_id’ => ‘20’,
    ‘title’ => ‘《哈利波特》’],
    [‘id’ => ‘13’,
    ‘user_id’ => ‘20’,
    ‘title’ => ‘《指环王》’]
    ]);
    //firstOrNew查阅如果表中没有符合的那就直接返回这条数据
    $user = User::find(20);
    return $user->book()->firstOrNew([‘title’ => ‘《三个代表》’]);
    //firstOrCreate查阅如果表中没有符合的那就直接创建一个到表里面并输出
    $user = User::find(20);
    return $user->book()->firstOrCreate([‘title’ => ‘《宇宙》’, ‘id’ => ‘11’]);
    PS: 还有findOrNew、firstOrNew、firstOrCreate和updateCreate方法;
    d. 有新增,自然有修改删除,直接使用delete()和update()方法即可;
    //关联删除,删除user_id = 26的书
    $user = User::find(26);
    $user->book()->delete();
    //关联修改,修改user_id=26的书
    $user = User::find(26);
    $user->book()->where(true)->update([‘title’=>’《宇宙学说》’]);
    e. 使用associate()方法来修改掉书籍关联的用户,即修改user_id;
    //修改关联的外键,即: user_id修改,换用户
    $user = User::find(20); //这里拿的是user表里的id
    $book = Book::find(11); //这里拿的是book表里的id
    $book->user()->associate($user);
    $book->save();

    PS:如果想取消一本书的拥有者,比如将user_id设置为null,字段要设置可以null;
    $book = Book::find(11);
    $book->user()->dissociate();
    $book->save();
    f. 搜索书籍的对应用户的时候,null字段会导致用户出现null数据;
    g. 我们可以采用空对象默认模型的方式,去解决这个问题;
    // Book.php
    public function user(){
    return $this->belongsTo(User::class, ‘user_id’, ‘id’)
    ->withDefault([
    ‘id’ => 0,
    ‘username’ => ‘游客用户’
    ]);
    }