laravel雄辩->不一对一地工作

现在我的产品模型中有这种方法

public static function product_lines($request)
{
    $keyword = Helper::clean_keyword($request['keyword']);
    $data = Product::where
    ('number','like','%'.$keyword.'%')->
    orWhere('name','like','%'.$keyword.'%')->
    with('get_unit_relations')-> // this is one to many 
    limit(30)->
    get();
    return $data;
}

and this is the get_unit_relations

public function get_unit_relations()
{
    return $this->hasMany('App\Models\Product_unit','product_id','id');
}

像这样,它的工作和返回数据没有任何问题..

{
    "id": 1,
    "number": "1",
    "name": "test",
    "foreign_name": null,
    "get_unit_relations": [
        {
            "id": 3,
            "unit_id": 2,
            "product_id": 1,
            "barcode": "455",
            "smallest_unit_relation": 12,
            "price": 12,
            "cost": null,
            "created_by": null,
            "deleted_by": null,
            "created_at": "2020-05-17T21:46:26.000000Z",
            "updated_at": "2020-05-17T21:46:26.000000Z",
            "deleted_at": null
        }
    ]
}

但是,如果我改变这样的代码..

public static function product_lines($request)
{
    $keyword = Helper::clean_keyword($request['keyword']);
    $data = Product::where
    ('number','like','%'.$keyword.'%')->
    orWhere('name','like','%'.$keyword.'%')->
    with('get_smallest_unit_id')-> // this is one to one 
    limit(30)->
    get();
    return $data;
}

这是get_smallest_unit_id

public function get_smallest_unit_id()
{
    return $this->hasOne('App\Models\Unit','id','smallest_unit_id');
}

我得到这样的回报..

{
    "id": 1,
    "number": "1",
    "name": "test",
    "foreign_name": null,
    "get_smallest_unit_id": null // it always return null in any one to one relaiton ..
}

how can i use ->with() method with one to one relation thanks

评论