php - 即使我在 laravel api 中获取不同的东西,也从数据库中获取错误的数据
问题描述
大家好,我正在开发一个 laravel 项目,用于制作用于以 json 格式传递数据库值的 api,但问题是我在这个表中有一个用户表 2 ids 1 是主键,第二个是业务 _id 我想根据business_id 但它通过 id 获取数据请帮助我如何解决这个问题。
这是我的模型代码
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class user extends Model
{
protected $table = 'business';
}
这是我的控制器代码
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\user;
class GetController extends Controller
{
public function databybusinessid($business _id){
$users = new user();
$users = user::find($business _id);
return response()->json($users);
}
}
太感谢了
解决方案
find() 通过其主键检索模型..
所以你必须使用你的代码:
$users = user::where('business_id',$business_id)->first();
// Notice first() Retrieve the first model matching the query constraints...
或者您可以更改模型中的主要代码
namespace App;
use Illuminate\Database\Eloquent\Model;
class user extends Model
{
protected $table = 'business';
protected $primaryKey = 'business_id';
}
推荐阅读
- c# - 即使在刷新根节点后,我们可以保持子节点扩展吗?在c#中
- apache-spark - Spark bulk insert 的 Elasticsearch 索引速度非常慢
- c++ - 在主窗口之前显示登录对话框并隐藏主窗口按钮
- ios - 从 mac 连接到 nat64 网络的设备中没有互联网
- javascript - 不同的字体源leaflet-awesome-marker和Leaflet-easy-button
- qt - 子类 Keys.onPressed 和 MouseArea.onClicked
- php - 获取多对多关系中的计数以进行记录编辑
- c# - 如何使用 jQuery 在弹出窗口中显示 JSON 解析数据
- xpath - 如何在 Firefox 开发者版中找到 XPath?
- sql - 从数字sql中的字符串替换多个值