【laravel5.4 + TP5.0】hasOne和belongsTo的区别

1、从字面理解:假如A比B大,那么A hasOne B; B belongsTo A;

2、个人总结:

3、从代码角度:

主要是看你是在哪一个model(模型)中编写这个关联关系,父关联对象就是在父关联model(本文是在Products的model类)下编写的关联模型。


has_one(或has_many):外键在子关联对象中

//父关联对象表
Products{
 id
 product_name
}
//子关联对象表
Image{
 image_id
 img_name
 product_id    //foreign key
}

//hasOne方法的参数包括:
//hasOne('关联模型名','外键名','主键名',['模型别名定义'],'join类型');
//默认的join类型为INNER
//写在Products的model类中
public function Img(){
  $this->hasOne('Image','product_id','id');
}

belongs_to:外键在你父联对象中

//父关联对象表:
Product{
 product_id
 img_id    //foreignkey
 product_name
}
//子关联对象表
Image{
 id      
 img_name
}


//belongsTo方法的参数包括:
//belongsTo(‘关联模型名’,‘外键名’,‘关联表主键名’,[‘模型别名定义’],‘join类型’);
//默认的join类型为INNER
//写在Products的model类中
public function Img(){
$this->belongsTo('Image','img_id','id');
}

laravel5.4中hasOne和belongsTo、hasMany区分:

/* 
         * 下面三种写法:第一种会报错(前提:在Admin模型写入users表的模型关系hasOne、belongsTo和hasMany)
         * 因为User模型,我们并没有写入position的模型关联方法 
         * 而Admin::XX 和new Admin 不报错,因为写入了position方法
         */
        $users =  new AppAdmin();
        $uuu = User::find($this->user_id)->position->pos_name;
        var_dump($uuu);
        $users =  new AppAdmin();
        $uuu = $users::find($this->user_id)->position->pos_name;
        var_dump($uuu);
        $uuu = Admin::find($this->user_id)->department->dep_name;
        var_dump($uuu);

//依据一个部门只能属于一个公司,而一个部门却可以有多个user,gogo

//$company_msg = Department::find(2)->company->company_name;  //【一对一】、【多对一】 这种是正确的,别动了
        $usernames = Department::find(6)->user()
                    ->where('is_del','<>','1')
                    ->pluck('username');   //一对多关系
        $username_arr = [];
        foreach($usernames as $v){
            $username_arr[] = $v;   //输出纯一维数组
        }
        var_dump($usernames);
        echo "<br>";
        var_dump($username_arr);
原文地址:https://www.cnblogs.com/xuzhengzong/p/8684469.html