laravel框架中hasOne和blongTo的用法详解

  1. 在某一个model class里面,class_name所对应的表为主表(父),
    关系函数方法里面的第一个参数所对应的表为从属表(子),
    即为与主表相关联的表。

$hasOne
1、外键保存在关联表中;
2、保存时自动更新关联表的记录;
3、删除主表记录时自动删除关联记录。

$belongsTo
1、外键放置在主表中;
2、保存时不会自动更新关联表的记录;
3、删除时也不会更新关联表的记录。

<?php

namespace App\Model;
use Illuminate\Database\Eloquent\Model;

  class ProformaInvoice extends Model
{
    use InsertCreator,InsertUpdator, BasicPaginate,Sort, SoftDeletes, PermissionFilter;
    protected $table = 'proforma_invoice';
    //表中的这些字段是可以赋值的
    protected $fillable = [
        'code',
        'sales_order_id',
        'invoice_no',
        'date',
        'seller_id',
        'buyer_id',
        'port_id',
        'updator_id',
        'updated_at'
        '''
        '''
    ];

    const STATUS_SAVED    = 1;  //保存
    const STATUS_AUDITED  = 2; //审核
    const STATUS_DISABLED = 3; //废弃
    static $field =['id', 'benebank', 'buyer_name', 'seller_company', 'sales_order_id'];

    protected $hidden = ['creator_id', 'deleted_at'];

    public function getId()
    {
        return $this->id;
    }

    public function seller()
    {
       return $this->belongsTo(CompanyAccount::class,'seller_id');//seller_id为在主表中(即ProformaInvoice)的外键
    }
  }

//同样的反写道理也是一样的

namespace App\Model;
use Illuminate\Database\Eloquent\Model;

  class CompanyAccount extends Model
{
    ...
    ...
    public function Proforma()
    {
       return $this->hasOne(ProformaInvoice::class,'Proforma_id','id');//Proforma为在关联表表中(即ProformaInvoice)的外键,id为主表(CompanyAccount)的主键;综合起来的意思就是主表中的id与从表中的Proforma_id关联匹配获取从表ProformaInvoice表中的查询数据
    }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值