Laravel 5.6.5关系执行错误查询

时间:2018-03-07 08:26:09

标签: php laravel eloquent laravel-eloquent laravel-5.6

正如您在下图中所看到的那样,shoporder和shoporderroutingstepplans之间的laravel关系并非如此。



我不知道我到底做错了什么,所以我希望有人可以帮助我。在下面的代码中,我在代码中留下了一些字段,以使其更清晰。

class shoporder extends Model
{
    protected $primaryKey = 'ID';

    protected $fillable = [
        'CADDrawingURL',
        'ID',
        'Costcenter',
        'CostcenterDescription',
        'Costunit',
        'CostunitDescription',
        'Created',
        'Creator',
        'CreatorFullName',
        'Description',
        'ShopOrderParent',
        'ShopOrderParentNumber',
        'ShopOrderRoutingStepPlanCount',
        'Status',
        'SubShopOrderCount',
    ];

    public function shopOrderRoutingStepPlans() {
        return $this->hasMany('App\shopOrderRoutingStepPlan', 'ShopOrder', 'ID');
    }
}

class ShopOrderRoutingStepPlan extends Model
{
    protected $primaryKey = 'ID';
    public $table = "shoporderroutingstepplans";
    protected $fillable = [
        'Account',
        'ID',
        'AccountName',
        'AccountNumber',
        'AttendedPercentage',
        'Backflush',
        'Created',
        'Creator',
        'CreatorFullName',
        'Description',
        'ShopOrder',
    ];

    public function shopOrder() {
        return $this->belongsTo('App\shopOrder', 'ShopOrder', 'ID');
    }
}

这是我执行的代码,用于获取控制器中1 shoporder的关系。

$orders = shopOrder::find('0600959e-6b92-4135-8ea8-1fa2fd92a916')->shopOrderRoutingStepPlans()->get();

在shoporder迁移中,我定义了主键:

$table->string('ID')->unique();
$table->primary('ID');

在shoporderroutingstepplans迁移中,我定义了外键,如下所示。

$table->string('ID')->unique();
$table->primary('ID');

$table->foreign('ShopOrder')
      ->references('ID')
      ->on('shoporders');

1 个答案:

答案 0 :(得分:0)

您必须切换最后两个参数的顺序:

 return $this->hasMany('App\shopOrderRoutingStepPlan', 'ShopOrder', 'ID');

 return $this->hasMany('App\shopOrderRoutingStepPlan', 'ID', 'ShopOrder');

参数是

  1. model,
  2. 链接模型中的列名称
  3. 模型中的列名称。