[英]Get data from 2 tables with a foreign key using Laravel model relationships
I have 2 tables 1) users 2) user_companies.我有 2 个表 1) 用户 2) user_companies。 A user belongs to or has one company, A company has many users.一个用户属于或拥有一个公司,一个公司有很多用户。 This is how I determined my relationships.这就是我确定人际关系的方式。 How can I pull company data for each user?如何为每个用户提取公司数据? Attempt to read property "company" on string - is the error I am receiving with my setup.尝试读取字符串上的属性“company”——这是我在设置时收到的错误。
Here is what I have tried so far and many other combinations but cant seem to figure out how to show the company name which is stored in the user_companies table under the company column.这是我到目前为止尝试过的方法和许多其他组合,但似乎无法弄清楚如何显示存储在 company 列下的 user_companies 表中的公司名称。 Not sure what I am missing here.不知道我在这里错过了什么。
user model用户 model
// Relationship between User and Company
public function company()
{
return $this->hasOne(Company::class, 'id','company_id');
//return $this->belongsTo(Company::class, 'company_id');
}
company model公司 model
public function user()
{
return $this->hasMany(User::class);
}
userController用户控制器
public function profile(User $user, Company $company)
{
$company = Users::with(['company']);
//$company = Company::with('user')->find('33');
return view('admin.users.profile', compact('user', 'company'));
}
blade file刀片锉刀
{{ $user->company->company }}
migration file (just added new column FK)迁移文件(刚刚添加了新列 FK)
Schema::table('users', function (Blueprint $table) {
$table->integer('company_id')->nullable()->unsigned();
$table->foreign('company_id')
->references('id')
->on('user_companies')
->onDelete('cascade');
});
First of all, you should change the relationship of user to company to belongsTo
:首先,您应该将用户与公司的关系更改为belongsTo
:
// User.php
public function company() :BelongsTo
{
return $this->belongsTo(Company:;class, 'company_id');
}
then eager load it by using with()
然后使用with()
急切地加载它
User::with('company')->get();
I solved this by doing the following.我通过执行以下操作解决了这个问题。
user model用户 model
public function company() :BelongsTo
{
return $this->belongsTo(Company::class, 'user_companies');
}
user controller用户 controller
public function profile(User $user, Company $company)
{
$company = Company::where('id', $user->company)->first();
return view('admin.users.profile', compact('user', 'company'));
}
profile blade file轮廓刀片文件
{{ $company->name }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.