首页 > 解决方案 > 如何让我雄辩的模型关系返回结果而不是空数组

问题描述

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

模型用户ProductListMap

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 和 where user_id = $userId

标签: phplaraveleloquent

解决方案


你错过了->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');
    }
}

推荐阅读