php - 如何在 laravel 中使用关系检索数据

标签 php mysql laravel

我正在尝试使用 laravel 中的关系检索数据,但我一直收到此错误。

Column not found: 1054 Unknown column 'orders.customers_id' in 'where clause' (SQL: select * from orders where orders.customers_id in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10))

在此之前我使用这些代码:

 $data = DB::table('customers')
        ->join('orders', 'orders.customer_id', 'customers.id')
        ->get();

    // convert to json string
    $data = json_decode(json_encode($data), true);
    return $data;

它返回我想要的确切结果是: enter image description here

这是我的客户表: enter image description here

订单表 enter image description here

订单

    class Orders extends Model
{
    public function customer(){
        return $this->belongsTo(Customers::class);
    }
}

客户

 class Customers extends Model
{
    public function order(){
        return $this->hasMany(Orders::class);
    }

数据 Controller

class DataController extends Controller
{
    public function all()
    {

        $All = Customers::with('order','order.customer_id')->paginate(10);

        return response()->json([
            'code' => 0,
            'success' => true,
            'data' => $All,
            'pagination' => [
                'current_page' => $All->currentPage(),
                'last_page' => $All->lastPage(),
                'prev_page_url' => $All->previousPageUrl(),
                'next_page_url' => $All->nextPageUrl(),
                'per_page' => $All->perPage(),
                'total' => $All->total(),
                'count' => $All->count(),
            ]
        ], 200);

最佳答案

你能试试这个吗

订单模型

class Orders extends Model
{
    public function customer(){
        return $this->belongsTo(Customers::class, 'customer_id');
    }
}

数据 Controller

class DataController extends Controller
{
    public function all()
    {

        $All = Customers::order()->paginate(10);

        return response()->json([
            'code' => 0,
            'success' => true,
            'data' => $All,
            'pagination' => [
                'current_page' => $All->currentPage(),
                'last_page' => $All->lastPage(),
                'prev_page_url' => $All->previousPageUrl(),
                'next_page_url' => $All->nextPageUrl(),
                'per_page' => $All->perPage(),
                'total' => $All->total(),
                'count' => $All->count(),
            ]
        ], 200);

我只是将外键放入了模型中。我不完全确定它应该在 Order Model 中还是在 Customer Model 中,无论哪种方式都尝试一下。

希望对您有所帮助!

关于php - 如何在 laravel 中使用关系检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57518399/

相关文章:

php - Laravel "artisan make:observer"失败

javascript - 从 PHP 将数据传递到 JavaScript 的替代方案?

javascript - JQuery 不会从偶数链接更改 div 的内容?

php - 在 LAMP 堆栈上,如何限制并发连接数并为超出该限制的用户提供静态页面?

php - 使用 MySQL 删除数据库表中除最后 30 行以外的所有行

php - 导入 XML Google 电子表格 - 帮助我编写 PHP 代码

php - 在简单表格中打印结果

MySQL 选择字段中具有最大值的行

php - 编辑 Laravel 中 Validator 的错误消息

javascript - 从 ajax 调用返回 html 并格式化它