Laravel无法获取所选配置文件的关系数据



我刚刚为用户创建了一个配置文件,希望显示与登录用户或其他选定用户相关的教育详细信息。

为此,我为用户创建了一个教育模型,并给出了双方的适当关系。我无法从登录用户或其他用户的教育表中获取任何数据。我在刀片文件中使用foreach标签。请审阅我的代码。谢谢。

教育模式

class Education extends Model
{
use HasFactory;
protected $primaryKey = 'education_id';
public function myusers()
{
return $this->belongsTo('AppModelsUser','user_id','education_id');
}
}

用户模型

public function myeducation()
{
return $this->hasMany('AppModelsEducation','education_id','user_id');
}
<<p>配置控制器/strong>
public function index()
{
$user = Auth::user();

return view('candidate.profile',['user'=>$user,]);
}

叶片文件

@foreach ($user->myeducation as $education)
<div>
{{  $education->school }}
</div>
@endforeach

教育与用户表结构

**Education Table**
{
Schema::create('education', function (Blueprint $table) {
$table->bigIncrements('education_id');
$table->bigInteger('user_id');
$table->string('school');
$table->string('degree');
$table->string('fieldOfStudy');
$table->date('startDate');
$table->date('endDate');
$table->string('grade');
$table->string('activities');
$table->string('description');
$table->timestamps();
});
}

用户表

$table->increments('user_id');
$table->bigInteger('role_id');
$table->bigInteger('membership_id')->nullable();
$table->string('firstname');
$table->string('lastname');

没有错误信息,只是空白

Table entries
DB::table('education')
'user_id' => '2',
'school' => 'University of Bedfordshire',
'degree' => 'MBA',

]);

DB::table('users')->insert([
'user_id' => '1',
'role_id' => '1',
'firstname' => 'Mohammed',
'lastname' => 'Sabeel',
.......
]);
DB::table('users')
' user_id' => '2'
'role_id' => '2',
'firstname' => 'zahida',
'lastname' => 'sabeel',
.......
]);

问题在于你们的关系第二和第三个论点。您传递密钥的方式不对。

Education

模型中的使用如下代码

public function myUser()
{
return $this->belongsTo('AppModelsUser', 'user_id');
}

如果使用主键表示关系,则不需要传递第三个参数。尽管您可以传递第三个参数来定义使用哪个列来连接表

public function myUser()
{
return $this->belongsTo('AppModelsUser', 'user_id', 'user_id');
// second argument user_id is from your education model while the third argument that is user_id is the primary key of your user model
// i have used singular name for the relationship name with camel case
}

现在在User模型

public function myEducations()
{
return $this->hasMany('AppModelsEducation', 'user_id');
// user_id is the user_id of education model
// and this is a has many relation i used plural form
}

在laravel doc中阅读更多关于关系的内容

在我们开始之前,请确保您的教育与登录用户相关联。

尝试加载你的关系。有时这对我很有效。
在配置文件控制器中,

public function index()
{
$user = Auth::user()->load('myeducation');

return view('candidate.profile',['user'=>$user,]);
}

即使它不工作,请分享你的表结构和表项。

最新更新