问题描述
我有 2 张桌子:
表User
:
表Product
:
和我有模型关系:
User
模型:
public function product() {
return $this->hasMany(Product::class);
}
Product
模型:
protected $fillable = [
'user_id','nama','harga','deskripsi','kategori_id','gambar',];
public function user()
{
return $this->belongsTo(User::class);
}
这是我的控制器:
class GetProductController extends Controller
{
public function index() {
$product = Product::with(['user'])->get();
if($product) {
return response()->json([
'success' => 1,'message' => 'success get data','products' => collect($product)
]);
} else {
return response()->json([
'success' => 0,'message' => 'Failed get data'
]);
}
}
}
这是我的路线 Api :
Route::get('getproduct',[GetProductController::class,'index']);
我想将 API 用于移动应用......而不是 Api web..
我得到的输出是:
我应该在控制器中更改什么?提前致谢... :) 我是 Laravel 的新手
解决方法
过去,您可以将 select 闭包传递到查询中以获取所需的列:
$product = Product::with(['user' => function($query) {
$query->select('id','name');
])
->get();
但是,使用 Laravel 8,您现在可以eager load the columns quicker
$product = Product::with(['user:id,name'])->get();
注意文档中的注释
使用此功能时,您应始终在要检索的列列表中包含 id 列和任何相关的外键列。
,添加产品型号
public function getUser()
{
return $this->hasOne('App\Models\User','id','user_id');
}
控制器
$product = Product::with(['getUser'])->get();
查看
@foreach ($product as $item)
{{ $item->getUser->name }}
@endforeach
,
加入方式:
class GetProductController extends Controller
{
public function index(){
$product = Product::join('users','users.id','products.user_id')
->select('users.name as user_name','products.*')->get();
if($product){
return response()->json([
'success' => 1,'message' => 'success get data','products' => collect($product) //get() method returns a collection,no need to collect again
]);
} else {
return response()->json([
'success' => 0,'message' => 'failed get data'
]);
}
}
}