Laravel不加载序列化模型的关系

时间:2019-05-09 10:37:19

标签: php laravel

我的工作很简单:

mockMvc.perform(get("/api/loans"))
            .andExpect(content().json(json));

class SampleJob extends Job implements ShouldQueue { use InteractsWithQueue, SerializesModels, DispatchesJobs; private $customer; public function __construct(Customer $customer) { parent::__construct(); $this->customer = $customer; } public function handle() { doSomeStuff($customer->currency()); } } 模型中,我与Customer有关系:

country

通过clas Customer extends Model { public function country() { return $this->belongsTo(Country::class); } public function currency() { return $this->country->currency(); } } 分派作业时,日志中出现错误:

dispatch(new SampleJob($customer))

这里的一个棘手的事情是,如果我从工作中删除 Call to a member function currency() on null {"code":0,"file":"Customer.php","line":386} 特质,它将正常工作。但是我真的不想这样做,因为它会导致无法预料的错误(我们有很多这样的工作,还有更多的属性)。

所以我只想弄清楚为什么会发生此错误。

我使用SerializesModels驱动程序进行作业。

Laravel 5.8.16。另外,使用Laravel 5.6可以正常工作。

1 个答案:

答案 0 :(得分:0)

建议在序列化时避免传递对象。在这种情况下,传递客户ID会更好:

class SampleJob extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels, DispatchesJobs;

    private $customerId;

    public function __construct(int $customerId)
    {
        parent::__construct();

        $this->customerId = $customerId;
    }

    public function handle()
    {
        $customer = Customer::find($this->customerId);

        doSomeStuff($customer->currency());
    }
}