如何在 Laravel 中正确使用 with() 关系?

发布于 2025-01-17 13:54:59 字数 2535 浏览 2 评论 0原文

我只是想澄清如何使用表中的关系。现在,我想从 employees 表中的 designation_id 获取 designation name 记录。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\{
    Designations,
    Positions
};

class Employees extends Model
{
    use HasFactory;

    protected $table = 'employees';

    protected $primaryKey = 'id';

    public $timestamps = true;
    
    protected $casts = [
        'designation_id' => 'array',
        'position_id' => 'array',
        'basic_pay' => 'decimal:2',
    ];

    protected $dates = ['created_at', 'updated_at'];

    protected $fillable = [
        'first_name', 
        'last_name',
        'designation_id',
        'position_id',
        'basic_pay',
    ];

    public function designations()
    {
        return $this->hasMany(Designations::class, 'id', 'designation_id');
    }

    public function positions()
    {
        return $this->hasMany(Positions::class, 'id', 'position_id');
    }
}

这是我的指定模型:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Employees;

class Designations extends Model
{
    use HasFactory;

    protected $table = 'designations';

    protected $primaryKey = 'id';

    public $timestamps = true;
    
    protected $dates = ['created_at', 'updated_at'];
    
    protected $fillable = [
        'name',
        'description'
    ];

    public function employees()
    {
        return $this->belongsTo(Employees::class, 'designation_id');
    }
}

这是我的 EmployeeController.php:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\{
    Employees,
    Designations
};

class EmployeesController extends Controller
{
    public function index()
    { 
        $employees = Employees::with('designations', 'positions')->get();
        return array_reverse($employees);     
    }
}

我检查了我的 api url,http://localhost:8000/api/employees 并收到此错误:

SQLSTATE[HY093]:无效的参数号(SQL:从designationswhereselect *代码>designations.idin (52))

I just wanted to clarify using the relationship in tables. Right now, I wanted to fetch records of designation names from designation_id in employees table.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\{
    Designations,
    Positions
};

class Employees extends Model
{
    use HasFactory;

    protected $table = 'employees';

    protected $primaryKey = 'id';

    public $timestamps = true;
    
    protected $casts = [
        'designation_id' => 'array',
        'position_id' => 'array',
        'basic_pay' => 'decimal:2',
    ];

    protected $dates = ['created_at', 'updated_at'];

    protected $fillable = [
        'first_name', 
        'last_name',
        'designation_id',
        'position_id',
        'basic_pay',
    ];

    public function designations()
    {
        return $this->hasMany(Designations::class, 'id', 'designation_id');
    }

    public function positions()
    {
        return $this->hasMany(Positions::class, 'id', 'position_id');
    }
}

Here's my designation model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Employees;

class Designations extends Model
{
    use HasFactory;

    protected $table = 'designations';

    protected $primaryKey = 'id';

    public $timestamps = true;
    
    protected $dates = ['created_at', 'updated_at'];
    
    protected $fillable = [
        'name',
        'description'
    ];

    public function employees()
    {
        return $this->belongsTo(Employees::class, 'designation_id');
    }
}

Here's my EmployeeController.php:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\{
    Employees,
    Designations
};

class EmployeesController extends Controller
{
    public function index()
    { 
        $employees = Employees::with('designations', 'positions')->get();
        return array_reverse($employees);     
    }
}

I checked my api url, http://localhost:8000/api/employees and got this error:

SQLSTATE[HY093]: Invalid parameter number (SQL: select * fromdesignationswheredesignations.idin (52))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

开始看清了 2025-01-24 13:54:59

我建议您安装phpstorm,它为您提供了功能参数的提示,并且您将不再存在此类问题。

正确格式是:

return $this->hasMany('App\Comment', 'foreign_key', 'local_key');

在您的名称模型中:

public function DesignationNames()
    {
        return $this->hasMany(\App\Models\Employees::class, 'designation_id', 'id');
    }

当您在控制器中检索它们时,您需要使用with()方法为:

名称:

然后,要访问相关员工集合中的属性,您需要:

$名称名称名称 -

I would recommend you to install phpstorm, it gives you hints of function parameters and you won't have this kind of issues anymore.

correct format is:

return $this->hasMany('App\Comment', 'foreign_key', 'local_key');

in your designations model:

public function DesignationNames()
    {
        return $this->hasMany(\App\Models\Employees::class, 'designation_id', 'id');
    }

When you retrieve them in your controller you need to use the with() method as:

Designations::with('DesignationNames')->get();

And then to access properties in the related employee collection you would need to:

$designation->DesignationNames->DesignationProperty

居里长安 2025-01-24 13:54:59

你的关系参数是错误的。如果

hasMany(class, foreignKey, relatedPrimaryKey)
# Employee
public function designations()
{
    return $this->hasMany(Designations::class, 'employee_id', 'id');
}

public function positions()
{
    return $this->hasMany(Positions::class, 'employee_id', 'id');
}

您渴望加载超过 1 个关系,请使用数组表示法。

此外,$employees 将是 Collection 的实例,因此您不能将其用作 array_reverse 的参数。

您可以使用集合方法来获得相同的结果,也可以使用 $employees->all() 来获取底层数组。

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employees;

class EmployeesController extends Controller
{
    public function index()
    { 
        $employees = Employees::with(['designations', 'positions'])->get();

        return $employees->reverse()->values()->all();
        // OR
        return array_reverse($employees->all());
    }
}

假设您的表具有如下结构:

Schema::create('employees', function (Blueprint $table) {
    $table->id();
    ...    
});

Schema::create('designations', function (Blueprint $table) {
    $table->id();
    $table->foreignId('employee_id')->constained('employees');
    ...
});

Schema::create('positions', function (Blueprint $table){
    $table->id();
    $table->foreignId('employee_id')->constained('employees');
    ...
});

由于您使用的是 increments 而不是 id(),因此代码必须稍有不同。

Schema::create('employees', function (Blueprint $table) {
    $table->increments('id')->unique();
    ...    
});

Schema::create('designations', function (Blueprint $table) {
    $table->increments('id')->unique();
    $table->unsignedInteger('employee_id');
    $table->foreign('employee_id')->references('id')->on('employees');
    ...
});

Schema::create('positions', function (Blueprint $table){
    $table->increments('id')->unique();
    $table->unsignedInteger('employee_id');
    $table->foreign('employee_id')->references('id')->on('employees');
    ...
});

Your relationships parameters are wrong. It's

hasMany(class, foreignKey, relatedPrimaryKey)
# Employee
public function designations()
{
    return $this->hasMany(Designations::class, 'employee_id', 'id');
}

public function positions()
{
    return $this->hasMany(Positions::class, 'employee_id', 'id');
}

If you're eager loading more than 1 relationship, use array notation.

Also, $employees will be an instance of a Collection, so you can't use it as an argument to array_reverse.

You can either use collection methods to achieve the same result, or use $employees->all() to get the underlying array.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employees;

class EmployeesController extends Controller
{
    public function index()
    { 
        $employees = Employees::with(['designations', 'positions'])->get();

        return $employees->reverse()->values()->all();
        // OR
        return array_reverse($employees->all());
    }
}

This is assuming your tables have a structure like this:

Schema::create('employees', function (Blueprint $table) {
    $table->id();
    ...    
});

Schema::create('designations', function (Blueprint $table) {
    $table->id();
    $table->foreignId('employee_id')->constained('employees');
    ...
});

Schema::create('positions', function (Blueprint $table){
    $table->id();
    $table->foreignId('employee_id')->constained('employees');
    ...
});

Since you're using increments instead of id(), the code has to be a little different.

Schema::create('employees', function (Blueprint $table) {
    $table->increments('id')->unique();
    ...    
});

Schema::create('designations', function (Blueprint $table) {
    $table->increments('id')->unique();
    $table->unsignedInteger('employee_id');
    $table->foreign('employee_id')->references('id')->on('employees');
    ...
});

Schema::create('positions', function (Blueprint $table){
    $table->increments('id')->unique();
    $table->unsignedInteger('employee_id');
    $table->foreign('employee_id')->references('id')->on('employees');
    ...
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文