我在网上搜索了一个小时,但无法弄清楚这一点。如果我们查看雄辩的关系文档:https://laravel.com/docs/5.2/eloquent-relationships https://laravel.com/docs/5.2/eloquent-relationships
用户模型示例:
<?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');
}
}
就在它的下面,如何访问 id=1 用户的电话号码:
$phone = User::find(1)->phone;
为什么phone
并不是phone()
有什么区别?
还有它是如何工作的?如果我尝试致电object->name
如果我的代码中没有括号,PHP 认为我正在寻找一个名为的类变量name
?
一些额外信息:
看起来phone正在返回对象(App\Models\Phone)并且phone()正在返回对象(Illuminate\Database\Eloquent\Relations\HasOne)
如果我运行下面的代码:
User::find(1)->phone->count()
框架执行以下 SQL 语句:
select * from `phone` where `phone`.`user_id` = '1' and `phone`.`user_id` is not null limit 1
select count(*) as aggregate from `phone`
如果我运行下面的代码:
User::find(1)->phone()->count()
框架执行以下SQL语句:
select count(*) as aggregate from `phone` where `phone`.`user_id` = '1' and `phone`.`user_id` is not null