雄辩地返回null

时间:2018-07-06 18:40:48

标签: laravel laravel-5 eloquent laravel-5.6

我需要选择国家名称(全名)作为country_name,但是我得到的是空值。有人知道我在做什么错吗?

我有以下查询:

$clinics = Clinic::select(
            'name', 'description', 'special_notes', 'email', 'phone_number', 'emergency_number', 'city', 'address',
            'zip', 'state', 'lat as latitude', 'lng as longitude', 'gmaps_link',
            'url as web_site', 'social_media', 'opening_hours', 'general_practice', 'specialist_and_emergency',
            'subscribe', 'accessibility'
        )->with(['country' => function($query) {
            $query->select('full_name as country_name');
        }])
        ->get()->toArray();

        dd($clinics);

具有以下关系:

诊所:

public function country()
    {
        return $this->belongsTo(Country::class, 'country_id', 'id');
    }

国家/地区:

public function clinic()
    {
        return $this->hasMany(Clinic::class);
    }

dd 为此数组提供

0 => array:21 [▼
    "name" => "Woodridge Vet Surgery"
    "description" => "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
    "special_notes" => "Holiday Special Notes for working hours"
    "email" => "info@woodridgevet.com.au"
    "phone_number" => "(07) 3209 4242"
    "emergency_number" => "Emergency Number"
    "city" => "Woodridge"
    "address" => "Shop 8, 91 Ewing Rd"
    "zip" => "QLD 4114"
    "state" => null
    "latitude" => "-27.6325612"
    "longitude" => "153.1091419"
    "gmaps_link" => null
    "web_site" => "http://www.woodridgevet.com.au"
    "social_media" => "[]"
    "opening_hours" => "{"friday-to": "18:00", "monday-to": "18:00", "sunday-to": "06:00", "friday-to2": "06:00", "monday-to2": "06:00", "sunday-to2": "06:00", "tuesday-to": "18:00", " ▶"
    "general_practice" => 1
    "specialist_and_emergency" => 1
    "subscribe" => 1
    "accessibility" => 0
    "country" => null
  ]

1 个答案:

答案 0 :(得分:3)

您应确保选择的国家/地区包括id。否则,口才无法将您找到的国家/地区与诊所模型的country_id列绑定。所以代替

->with(['country' => function($query) {
     $query->select('full_name as country_name');
 }])

您应该使用:

->with(['country' => function($query) {
     $query->select('id', 'full_name as country_name');
 }])