zoukankan      html  css  js  c++  java
  • laravel5.1 关联模型保存的方法(使用associate方法)

    模型定义

    class User
    {
    
        public function customer()
        {
            return $this->hasOne('Customer');
        }
    
    }
    
    class Customer
    {
    
        public function user()
        {
            return $this->belongsTo('User');
        }
    
    }
    

      

    需要注意的是 associate 方法是 BelongsTo 类才有,所以正确的调用方法如下:

    $user = new User($data);
    $customer = new Customer($customerData);
    
    $customer->user()->associate($user);
    $customer->save();
    

      

    与此相反的方法是 disassociate 方法:取消两个模型之间的 belongsTo 关联

    $customer->user()->disassociate();
    $customer->save()

    此方法需要注意的是,disassociate 并不会删除记录,只是更新关联的字段为 null 

    附(通过关联的模型保存):

    $user = new User($data);
    $user->save();
    
    $customer = new Customer($customerData);
    $user->customer()->save($customer);
    

      

  • 相关阅读:
    python的Collections 模块
    python模块
    python类
    python异常
    python文件处理
    python函数
    python字符串
    python数据结构
    python循环
    下载Google Play外国区APP技巧
  • 原文地址:https://www.cnblogs.com/eleven24/p/8097476.html
Copyright © 2011-2022 走看看