【问题标题】:Laravel - Eloquent relationship (hasMany) issuesLaravel - 雄辩的关系(hasMany)问题
【发布时间】:2019-08-29 13:10:50
【问题描述】:

又是一个雄辩的关系问题 :) 我希望有人能帮助我!

ProductionOrder.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductionOrder extends Model
{  
    public function workOrders()
    {
        return $this->hasMany('App\WorkOrder');
    }
}

WorkOrder.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class WorkOrder extends Model
{
    public function productionOrder()
    {
        return $this->belongsTo('App\ProductionOrder');
    }
}

因此,ProductionOrder 应该有一个或多个 WorkOrder。

生产订单迁移

public function up()
{
    Schema::create('production_orders', function (Blueprint $table) 
    {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('production_order_id')->unique();
        $table->longText('notes')->nullable();
        $table->timestamps();
     });
}

工单迁移

public function up()
{
    Schema::create('work_orders', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('work_order_id')->unique();
        $table->unsignedBigInteger('production_order_id'); 
     });
 }

ID 名称不只是“id”的原因是因为我从外部 API 导入订单数据。我认为这就是为什么关系不起作用但我似乎无法修复它的原因。

ProductionOrder::with('workOrders')->get();

上面为每个生产订单在work_orders属性中返回一个空数组,但是在数据库中肯定有工作订单与现有production_order_id

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:

    修复它,必须将production_order_id 的两倍添加到hasMany 关系:

     public function workOrders()
     {
         return $this->hasMany('App\WorkOrder', 'production_order_id', 'production_order_id');
     }
    

    【讨论】:

    • 这不是加两次。您在关系中明确提及您的相关列(键)。默认情况下,它将采用 id 而不是 'production_order_id` 。所以这里你提到不要拿id,取production_order_id
    【解决方案2】:

    使用这样的查询你肯定会得到数据

     class ProductionOrder extends Model
        {  
            public function workOrders()
            {
                //use this
                //return $this->hasMany(WorkOrder::class, 'id of workorder table which forigne key of', 'primary key of this table');
     return $this->hasMany(WorkOrder::class, 'production_order_id', 'id');
    
    //instead of
                //return $this->hasMany('App\WorkOrder');
            }
        }
    
    ProductionOrder::where('production_order_id', '=', 70600)->with('workOrders')->first();
    

    【讨论】:

    • 请根据我的建议添加关系键,让我知道我确定这会起作用
    猜你喜欢
    • 1970-01-01
    • 2019-03-17
    • 2014-10-18
    • 2016-09-28
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    相关资源
    最近更新 更多