父表
users
schema | 'id','email','pass'
关系
public function profile()
{
return $this->hasOne('App'Profile','user_id');
}
其他表
profiles
schema | 'id','user_id'/*foreign key to users table */ ,'address','city'
关系
public function user()
{
return $this->belongsTo('App'User','id');
}
我正在查询Profile
模型,并希望它渴望加载User
模型。
public function edit($id){
$profile = 'App'Profile::with('user')->where('id','=',$id)->get();
dd($profile);
}
这样我就可以加载用户的配置文件进行编辑,以及来自email
和pass
等模型User
详细信息数据。
这将返回user
的空关系??
此外,在刀片中,当使用$profile->user->email
时会出错
未定义的属性:Illuminate''Database''Eloquent''Collection::$user (查看: C:''xampp''htdocs''laravel1''resources''views''profile''edit.blade.php)
这是dd()
输出 http://bit.ly/1dA0R5p
它返回带有user
关系的 null,这就是我怀疑导致刀片错误的原因undefined property
。
这种方法可能吗?我的关系正确吗?
附言早些时候,我在查询模型并急切加载模型时遇到了反之亦然的情况User
Profile
并且有效。
片段
$users = 'App'User::with('group','profile')->get(); //This was working
您会收到null
,因为您的关系定义是错误的。您的profile
模型应该是
public function user()
{
return $this->belongsTo('App'User','user_id');
}
此错误是因为您尝试从集合中获取user
对象。
由于您已使用get()
检索数据,因此您收到的是配置文件集合,而不是单个配置文件。如果你想要一个配置文件,请使用 first()
方法而不是 get()
,否则在循环中使用它。
@foreach ($profiles as $profile)
{{ $profile->user->email }}
@endforeach
如果子模型中存在此行,请删除use SoftDeletes;
。
namespace App;
use Illuminate'Database'Eloquent'Model;
//use Illuminate'Database'Eloquent'SoftDeletes;
use App'User;
class Profile extends Model
{
// use SoftDeletes;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'profile';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['address', 'user_id'];
protected $primaryKey = 'user_id';
public function user() {
return $this->belongsTo('App'User');
}
}
现在设置$primaryKey = 'user_id';
在父模型中:
public function profile(){
return $this->hasOne('App'Profile');
}
因此,您可以检索用户配置文件
$profile = $user->profile? : new Profile;