首页 > 解决方案 > 即使我在 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);
}
}

太感谢了

标签: phpmysqllaravelapierror-handling

解决方案


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

}

推荐阅读