Php laravel json选择客户对象使用hasMany选择特定数据

Php laravel json选择客户对象使用hasMany选择特定数据,php,mysql,laravel,laravel-5,Php,Mysql,Laravel,Laravel 5,如何选择客户对象选择特定数据 模型用户已连接到客户hasMnay public function customer() { return $this->hasMany('App\Models\Customer','employe_id','id'); } 和用户控制器 $collection = User::with('customer')->where(['director_id'=> 16])->select('id','name'

如何选择客户对象选择特定数据

模型用户已连接到客户hasMnay

 public function customer()
    {
        return $this->hasMany('App\Models\Customer','employe_id','id');
    }
和用户控制器

$collection = User::with('customer')->where(['director_id'=> 16])->select('id','name',)->get();
        return $collection;
及回应

[
    {
        "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
            },
            
        ]
    },
]
User::whereHas('customer',函数($query){
返回$query->where('director_id','=',16);
})->get();
试试看

控制器

$customers = [];
foreach($collection as $item) {

    $customers[] = $item->customer;
}

return $customers;
看法


您可以加载特定的列

对于您的情况,如果您只想选择客户的
地址
显示所有者姓名

$collection = User::with('customer:address,shop_owner_name')->where(['director_id'=> 16])->select('id','name',)->get();

return $collection;

选择什么?什么表格的哪些特定数据?您希望输出是什么?地址中的客户、店主名称您可以限制该关系的选择,但仍需要选择外键
员工id
,以便Elotent可以将孩子与父母匹配您认为应该在哪里应用该
语句,因为它看起来不像您的
用户
有基于此输出的字段。。。另外,
customer
可能应该是
customers
(复数),因此您知道这是一个“多”关系。api Post中没有返回空列表。您可能需要根据您的特定用例对其进行更多修改。这个链接信息量很大。
$collection = User::with('customer:address,shop_owner_name')->where(['director_id'=> 16])->select('id','name',)->get();

return $collection;
$collection = User::with('customer'=> function($query) {
     $query->select(['id','name']);
 })->where(['director_id'=> 16])->select('id','name',)->get();
        return $collection;