作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 laravel 中的关系检索数据,但我一直收到此错误。
Column not found: 1054 Unknown column 'orders.customers_id' in 'where clause' (SQL: select * from
orders
whereorders
.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;
订单
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/
我是一名优秀的程序员,十分优秀!