php - 如何让我雄辩的模型关系返回结果而不是空数组
问题描述
我想查询模型以在满足特定条件时返回结果,如果我不包含 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
解决方案
你错过了->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');
}
}
推荐阅读
- quart - 在 Hypercorn 后面运行 Quart
- r - 是否可以使用 R 将 .shp 或 .tif 文件转换为具有值的网格?
- azure - Azure Active Directory 密码重置
- javascript - Google Apps 脚本 + Pipedrive API “JavaScript 运行时意外退出。” 错误
- sql - SSRS 将多值文本参数转换为 SQL 语法中的字符串
- sql - 将查询结果中的一列附加到 SQL 中的另一列
- angular - 没有重载与角度上的此调用相匹配
- java - 我该如何解决这个中断标签问题?
- sql - 如何在 GORM 中选择年份
- laravel - 自动登录上的 Laravel 事件监听器(记得我)?