how to select customer object select perticular data
model user has connected to customer hasMnay
public function customer()
{
return $this->hasMany('App\Models\Customer','employe_id','id');
}
and user controller
$collection = User::with('customer')->where(['director_id'=> 16])->select('id','name',)->get();
return $collection;
and response
[
{
"id": 25,
"name": "emp1",
"customer": [
{
"id": 9,
"shop_owner_name": "afs",
"email": "a@gmail.com",
"address": "a",
"lat_lng": "a",
"shop_name": "a",
"shop_license": "a",
"contact_number": "1234567890",
"shop_image": "image/rU54qz67G9pJ7xEc8JSMkZAzxgUE5pb98zQPelMt.png",
"customer_image": "image/0ylk6OfMGwOqsdcUXpVZapOpPL73oO0gtOk7PXYV.png",
"director_id": 0,
"employe_id": 25
},
]
},
]
Controller
$customers = [];
foreach($collection as $item) {
$customers[] = $item->customer;
}
return $customers;
View
@foreach ($collection as $item)
@foreach($item->customer as row)
{{ $row->email }}
@endforeach
@endforeach
$collection = User::with('customer'=> function($query) {
$query->select(['id','name']);
})->where(['director_id'=> 16])->select('id','name',)->get();
return $collection;
User::whereHas('customer', function ($query) {
return $query->where('director_id', '=', 16);
})->get();
Try that!
https://laravel.com/docs/8.x/eloquent-relationships#constraining-eager-loads
You can eager load specific columns https://laravel.com/docs/8.x/eloquent-relationships#eager-loading-specific-columns
For your case if you want to only select address
and show_owner_name
of the customer:
$collection = User::with('customer:address,shop_owner_name')->where(['director_id'=> 16])->select('id','name',)->get();
return $collection;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.