【问题标题】:Laravel eloquent relationship between tablesLaravel 雄辩的表之间的关系
【发布时间】:2019-11-06 22:26:53
【问题描述】:

陷入了 Laravel 雄辩的关系中。我有两张桌子。

燃料包含

  • id、fuel_name、fuel_rate

机器包含

  • id, machine_name, machine_ratefuel_id

    字段。

fuel_id 是一个外键。

我尝试了一些来自 laravel.com 的示例

Machine.php

class Machine extends Model
{
    protected $table = 'machine';

    public  function machineinfo()
    {
        return $this->hasMany('App\Fuel','id');
    }
}

在控制器中

$items = Machine::find(1)->machineinfo;

我想看看 输出中的机器名称、机器代码、燃料名称和燃料率。

但是输出是

找不到列:1054 'where 子句'中的未知列'fuel.machine_id'(SQL:select * from fuel where fuel.machine_id = 1 和 fuel.machine_id 不为空)

【问题讨论】:

    标签: laravel laravel-5 orm eloquent


    【解决方案1】:

    请在此处查看 laravel hasMany 部分的结尾: https://laravel.com/docs/5.8/eloquent-relationships#one-to-many

    hasMany 的第二个参数是一个外键,在这种情况下,这意味着 ma​​chine 表中的 fuel_id。因此,不要将 'id' 作为第二个参数传递,您应该在

    中发送 'fuel_id'

    $this->hasMany('App\Fuel','fuel_id').

    另外,您可能不需要使用第二个参数。请参阅上面同一链接中的命名约定。根据提供的App\Fuel 类自动检测外键。

    【讨论】:

      猜你喜欢
      • 2018-07-24
      • 2019-07-01
      • 1970-01-01
      • 2020-07-23
      • 2016-09-06
      • 2015-03-14
      • 2018-11-28
      • 2015-01-11
      • 2021-06-03
      相关资源
      最近更新 更多