gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:04:46 26 4
gpt4 key购买 nike

我正在尝试使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com