简体   繁体   中英

How do I get my eloquent model relationships to return results instead of empty array

I want to query a model to return results when a specific condition is met, I get results if I dont include where clause but once I include where clause I get an empty array, I have checked all the values and they exist in the DB

Model 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');
    }
}

Repository

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');
    }
}

I want to get results from usershoppinglistmap where shopping_list_id = $listId and where user_id = $userId

You missing the ->get()

try to update your code as following:

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');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM