如何获得雄辩的模型关系以返回结果而不是空数组

时间:2019-07-14 06:30:11

标签: php laravel eloquent

我想查询一个模型以在满足特定条件时返回结果,如果不包含where子句,我会得到结果,但是一旦包含where子句,我就会得到一个空数组,我检查了所有值并且它们存在于数据库

模型UserProductListMap

class UserProductListMap extends UuidModel
{
    protected $table = 'user_product_list_map';

    public function product()
    {
        return $this->belongsTo('App\Models\UserProduct', 'product_id',             'uuid');
    }

    public function lists()
    {
        return $this->hasMany('App\Models\UserShoppingList',   'shopping_list_id', 'uuid');
    }
}

存储库

public function getUserListMappings($listId, $userId)
{
    try {
       $produc = Models::with('lists')->where('uuid',$listId);
       $data =[];
       foreach ($produc as $products) {
            $data = $products;
       }
       return $data;
        //$result =  $this->getModel()->first();
        //$result = $result->product->name;

    } catch (QueryException $exception) {
        throw new ResourceGetError('Product');
    } catch (\PDOException $exception) {
        throw new ResourceGetError('Product');
    }
}

我想从usershoppinglistmap获得结果,其中shopping_list_id = $ listId,而user_id = $ userId

1 个答案:

答案 0 :(得分:1)

您错过了->get()

尝试如下更新代码:

public function getUserListMappings($listId, $userId)
{
    try {
       // add the missing ->get()
       $produc = Models::with('lists')->where('uuid',$listId)->get();
       $data =[];
       foreach ($produc as $products) {
            $data = $products;
       }
       return $data;
        //$result =  $this->getModel()->first();
        //$result = $result->product->name;

    } catch (QueryException $exception) {
        throw new ResourceGetError('Product');
    } catch (\PDOException $exception) {
        throw new ResourceGetError('Product');
    }
}
相关问题