[英]how to retrieve data using relationship in laravel
我正在尝试使用laravel中的关系来检索数据,并且一直都收到此错误。
未找到列:1054“ where子句”中的未知列“ orders.customers_id”(SQL:从
orders
所在的orders
选择*。(1、2、3、4、5、6、7、8、9、10中的customers_id
) )
在此之前,我使用了以下代码:
$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);
}
数据控制器
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');
}
}
数据控制器
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
中尝试两种方式。
希望能帮助到你!
从Customers::with('order','order.customer_id')->paginate(10);
删除order.customer_id
Customers::with('order','order.customer_id')->paginate(10);
所以应该
Customers::with('orders')->paginate(10);
另外,因为客户可以有很多订单,所以最好将您的关系命名为orders
class Customers extends Model
{
public function orders()
{
return $this->hasMany(Orders::class);
}
}
在我的控制器中
$All = Customers::with('order')->paginate(10);
return response()->json([
'code' => 0,
'success' => true,
'data' =>$All
], 200);
客户模型
class Customers extends Model
{
public function order(){
return $this->hasMany(Orders::class,'customer_id','id');
}
}
订单模型
class Orders extends Model
{
public function customers(){
return $this->belongsTo(Customers::class,'customer_id','id');
}
}
及其作品。 但是还有一件事我不理解。 它的工作要么在“ Customers model
或“ Orders model
定义关系,要么在两者中定义关系
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.