我有2个数据库表=> mobile_phones
,mobile_users
mobile_phones
phone_id(主键,auto_increment)
phone_name(varchar(150))
phone_model(int(11))
mobile_users
user_id(主键,auto_increment)
用户名(varchar(150))
mobile_phone_id(外键引用mobile_phones(phone_id))
mobile_phones
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class MobilePhone extends Model
{
protected $primaryKey = "phone_id";
public $timestamps = false;
protected $table = "mobile_phones";
protected $fillable = array("phone_name","phone_model");
public function mobileUser()
{
return $this->hasOne("MobileUser","mobile_phone_id");
}
}
mobile_users
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class MobileUser extends Model
{
protected $primaryKey = "user_id";
public $timestamps = false;
protected $table = "mobile_users";
protected $fillable = array("username","mobile_phone_id");
public function mobilePhone()
{
return $this->belongsTo("MobilePhone","phone_id");
}
}
我正在尝试在MobileUser
和MobilePhone
模型之间建立一对一的关系,但事实并非如此。以下是我在Controller的操作中的代码 -
public function query()
{
$getUsername = MobilePhone::find(1)->username;
echo $getUsername;
}
当我执行NULL
时,上面的代码为我var_dump()
我确实在SO上检查了类似的问题,他们使用with()
(但这不是必需的)。我指的是Laravel 5.2文档,他们说我们可以使用Eloquent的动态属性访问另一个关系中的关联记录。该文档的链接是here
请帮助!!
答案 0 :(得分:0)
这样的事情:
public function query()
{
$getUsername = MobilePhone::find(1)->mobileUser;
echo $getUsername->username;
}
答案 1 :(得分:0)
这样做时:
public function query()
{
$getUsername = MobilePhone::find(1)->username;
echo $getUsername;
}
您尝试从username
号码中访问MobilePhone
属性,这是不正确的。
试试这个:
public function query()
{
$getUsername = MobilePhone::find(1)->mobileUser->username;
echo $getUsername;
}
另外,我鼓励您使用with
语句,因为它会预加载所需的所有依赖项(意味着单个查询),而不是急于加载它(许多查询)
答案 2 :(得分:0)
您需要调用模型的功能,所以请执行以下操作
public function query()
{
$getUsername = MobilePhone::find(1)->mobileusers;
echo $getUsername->username;
}