I have two models, Fair and Coordinate. Coordinate has many Fair's.
When retrieving the related Coordinate from Fair, I only want to return Longitude and Latitude, no timestamps or the ID.
When I run $fairs = Fair::with('coordinates')->get(); The Coordinate relation is Null.
If I change the select method on the belongsTo in Fair model to return $this->belongsTo('App\Coordinate', 'coordinate_id')->select(array('id', 'longitude', 'latitude'));
The response is correct, but it includes the ID.
"coordinates":{
"id": 1,
"longitude":"-25.704571",
"latitude":"59.145973"
},
Is there a way to use the select method without including the ID?
I found if I also add protected $hidden = ['id']; to the Coordinate model, the response I want is correct.
"coordinates":{
"longitude":"-25.704571",
"latitude":"59.145973"
},
This doesn't seem like the correct way to do it.
Fair:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Fair extends Model
{
protected $dateFormat = 'c';
public function coordinates()
{
return $this->belongsTo('App\Coordinate', 'coordinate_id')->select(array('longitude', 'latitude'));
}
}
Coordinate:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Coordinate extends Model
{
protected $fillable = ['longitude', 'latitude'];
public function fairs()
{
return $this->hasMany('App\Fair');
}
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire