Php 雄辩的查询总是使用oneToOne关系为父表返回null
父表Php 雄辩的查询总是使用oneToOne关系为父表返回null,php,laravel,eloquent,laravel-5,one-to-one,Php,Laravel,Eloquent,Laravel 5,One To One,父表 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 use
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
model,希望它与User
model一起加载
public function edit($id){
$profile = \App\Profile::with('user')->where('id','=',$id)->get();
dd($profile);
}
因此,我可以加载用户的配置文件进行编辑,以及来自用户
模型的详细数据,如电子邮件
&密码
等
这将为用户
返回一个空关系
另外,在刀片服务器中访问$profile->user->email
时出现错误
未定义的属性:Illumb\Database\Eloquent\Collection::$user
(观点:
C:\xampp\htdocs\laravel1\resources\views\profile\edit.blade.php)
这是dd()
输出
它返回带有user
关系的null,我怀疑这是blade中未定义属性
错误的原因
这种方法可行吗?我的关系正确吗
p.S.早些时候,我在查询用户
模型和急切加载配置文件
模型时遇到了一个反之亦然的情况,这很有效。片段
因为您的关系定义错误,您将收到的
null
。您的配置文件
型号应为
public function user()
{
return $this->belongsTo('App\User','user_id');
}
错误是因为您试图从集合中获取user
对象
由于您使用了get()
来检索数据,因此您收到的是一组配置文件,而不是一个配置文件。如果需要单个概要文件,请使用first()
方法而不是get()
,否则请在循环中使用它
@foreach ($profiles as $profile)
{{ $profile->user->email }}
@endforeach
删除
使用软删除代码>如果子模型中存在此行
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;
成功了。中的快速跟进问题从配置文件
模型到
关系,第二个参数应该是键
,用于在用户
表上识别用户,对吗?因此,我是否应该在users
表中创建一个profile\u id
外键?是的,它是外键。不,这样不行belongsTo
关系使用当前表的外键获取关系数据。所以在profiles
表上有user\u id
就足够了。在用户
表上不需要配置文件id
。这就清楚了。谢谢:-)
$profile = $user->profile? : new Profile;