首先,在我的mysql数据库中,我有两个名为“users”和“users_details”的表,它们处于关系中
用户表
id(PK,AI,INT),用户名(VARCHAR,UNQ),密码(VARCHAR), fullname(VARCHAR)
和users_table
id(PK,AI,INT),电子邮件(VARCHAR),电话(VARCHAR),地址(VARCHAR),has_record(VARCHAR), user_id(int,FK =参考表'users.id')
和我的模型绑定。
'用户'模型
WWW-Authenticate
和'users_details'模型
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['username', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
public function user_details(){
return $this->hasOne('App\users_details');
}
}
我知道我可以这样做
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class users_details extends Model {
protected $table = "user_details";
public function ud()
{
return $this->belongsTo('App\User');
}
}
但是我想从'User'表中获取fullname记录,这是'users_table''user_id'外键的主要参考表?怎么做?我试过了
$data = User::find(1)->with('user_details'); //or
$data = User::find(1)->user_details;
但不幸的是,遗憾的是没有工作,有任何帮助,想法,线索,建议,建议吗?
更新:
我使用“查询构建器”
实现了它$data = users_details::where('has_record', '=', 'no')->with('ud')->get(); //get all the records where column 'has_record' of 'users_details' is equal to 'no'
$data = $data->ud->fullname; //get the fullname
但是有没有办法使用Eloquent的力量来做到这一点?
答案 0 :(得分:1)
你可以这样做。
根据您的代码
使用用户渴望加载查找一个用户详细信息并获取名称。
$user_detail = user_details::with('ud')->find(1);
$user_detail->ud->name;
使用用户渴望加载获取所有用户详细信息并获取用户名。
$user_details = user_details::with('ud')->get();
foreach($user_details as $user_detail){
echo $user_detail->user->name;
}
如果你愿意,我会给你一个建议。 尝试遵循单数/复数格式,这可以使代码更具可读性。
// User Classs.
public function user_detail(){
return $this->hasOne('App\UserDetail');
}
// UserDetail Class.
public function user(){
return $this->belongsTo('App\User');
}