关于模型关联 hasOne 和 belongsTo 的使用场景和 sql 语句
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}
$phone = User::find(1)->phone;
请问执行的sql是如何的?如何验证和查出来呢?
然后和belongsTo
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
/**
* 获得拥有此电话的用户
*/
public function user()
{
return $this->belongsTo('App\User');
}
}
$user = Phone::find(1)->user;
有什么不同呢?
如何判断用hasOne还是belongsTo呢?
关于 LearnKu
自问自答
hasone 和 belongsto 主要看表设计 主表 从表的区别
主表(父表) 在数据库中建立的表格即 Table,其中存在主键 (primary key) 用于与其它表相关联,并且作为在主表中的唯一性标识。
从表(子表) 以主表的主键(primary key)值为外键 (Foreign Key) 的表,可以通过外键与主表进行关联查询。从表与主表通过外键进行关联查询。
主表用 hasone 从表用 belongsto
belong的英文中就有属于的意思,所以在从表中用关联肯定是用belongsto。
概念上自问自答了。那我推一个打印请求过程中
SQL打印到log的插件吧 overtrue/laravel-query-logger :blush: