【问题标题】:Laravel Eloquent Relationship for lookup table用于查找表的 Laravel Eloquent 关系
【发布时间】:2021-12-23 13:05:28
【问题描述】:

我有一个名为 Item 的模型和一个名为 Unit 的模型 我正在尝试制作库存系统

项目模型表是 项目 ID 姓名 描述 location_id 数数 unit_id type_id provider_id

对于单元模型 单位 ID 姓名 说明

在项目模型中我有这个公共功能

class Item extends Model
{
    use HasFactory;

    public function unit() {
        return $this->belongsTo('Unit', 'id');
    }
}

在单元模型中

class Unit extends Model
{
    use HasFactory;

    protected $table = 'units';

    public function items(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany('Item', 'id');
    }
}

并检查我发现 laravel SQL 的数据库日志是

select * from "units" where "units"."item_id" = $1 and "units"."item_id" is not null

当我在修补程序中这样做时

$item = App\Models\Stock\Item::find(1);
$item->unit

如何解决这个问题并告诉 laravel 发送类似的 SQL

select * from "units" where "units"."id" = $1 and "units"."id" is not null

id 值在哪里?

提前致谢

马丁

【问题讨论】:

  • 我刚刚得知这是一个“查找表”问题,所以我更改了标题
  • 我刚刚用我在博客中找到的方法更新了我的模型,但仍然无法正常工作
  • 看看这个:laravel.com/docs/8.x/eloquent#primary-keys。 Laravel 假设你的表 PK 是 'id',但你可以显式设置你自己的列名。
  • 其实我确实明确设置了。我更新了我的方法,以便使用密钥“id”但没有运气

标签: laravel one-to-one eloquent-relationship


【解决方案1】:

嗯...我正在修补程序中测试这个。我正在更改模型但没有重新启动修补程序

显然需要在更改模型后重新启动 tinker 才能测试

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 2015-11-28
    • 2013-10-03
    • 2017-07-19
    • 2018-06-19
    • 1970-01-01
    • 2016-05-02
    • 2015-01-01
    • 2021-05-09
    相关资源
    最近更新 更多