【发布时间】:2021-09-07 22:40:22
【问题描述】:
我正在 Laravel 8 项目中查询公司详细信息。下面是结构和 MySQL 查询。
# Getting company param from request.
SELECT c.company_name, p.position_name, s.salary
FROM tbl_company as c
JOIN tbl_company_type as t ON t.id = c.company_type_id
JOIN tbl_company_position as p ON p.company_id = c.id
JOIN tbl_comapny_salary as s ON s.position_id = p.id
where c.id = 1
表结构:
| tbl_company_type |
|---|
| id |
| type |
| description |
| tbl_company |
|---|
| id |
| company_type_id |
| company_name |
| description |
| tbl_company_position |
|---|
| id |
| position_name |
| company_id |
| tbl_comapny_salary |
|---|
| id |
| position_id |
| salary |
公司模型
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
protected $table = 'tbl_company';
public function listtype()
{
return $this->hasOne(Type::class, 'id', 'company_type_id');
}
public function listposition()
{
return $this->hasOne(Type::Position, 'company_id', 'id');
}
}
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Type extends Model
{
protected $table = 'tbl_company_type';
}
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Position extends Model
{
protected $table = 'tbl_company_position';
public function listsalary()
{
return $this->hasOne(Type::Salary, 'position_id', 'id');
}
}
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Salary extends Model
{
protected $table = 'tbl_comapny_salary';
}
使用关系检索公司详细信息
$companydetails = Company::with('listtype', 'listposition','listsalary')-
>whereRaw("tbl_company = 2")->get();
收到此错误
message": "调用模型上未定义的关系 [listsalary] [应用\模型\位置]
【问题讨论】:
-
不确定,但是,我认为错误即将到来,因为在职位模型上声明了关系列表,并且您正尝试从公司模型访问它
-
但我认为你在 Company 模型中调用了关系方法,如果你想加载它,我认为你必须像
$companydetails = Company::with('listtype', 'listposition.listsalary')- >whereRaw("tbl_company = 2")->get();那样重写,因为 Position 是具有这种关系的那个
标签: php laravel laravel-8 eloquent-relationship