Laravel:雄辩的关系突然停止了工作

Laravel:雄辩的关系突然停止了工作

问题描述:

After a recent update to my live environment, I got some errors about case sensitive model names that were not found but I fixed those quite fast. Now, after about a week after this update I suddenly receive errors about "property of non object" while trying to access related objects. Here are my models:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class products extends Model {
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'v_products_2';
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class order extends Model {
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'v_customers_orders';

    public function getProduct (){
        return $this->belongsTo('App\products', 'product_id', 'product_id');
    }   
}

I've setup my routes and middlewares correctly and after trying to access a property like this will result in an "non-object" error:

echo $orders->getProduct->product_id;

However this exact same code worked like 2 hours ago and has been working for several months now. Except that, this code also works on my Windows Homestead environment making it very hard for me to troubleshoot it. The only way I was able to reproduce this error locally, was to remove the getProduct function from the model. But on live, I get the same behaviour either way.

The issue was that my orders table had some entries of products that were deleted from the products table. The result was that an array was returned instead of an object. Deleting/editing the problematic rows made the code work again as before.

Try to change class names, to first letter uppercase, and then relation App\Products.

You will get a non-object error when your get_product() function returns a value null. Try to add a condition to check null value before calling the property.