[英]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.