Hi, I've read the eloquent docs, but can't seem to find the answer - am I missing something?
I am trying to achieve the Eloquent equivalent of this MySQL statement:
select model.model_name from manufacturer, model where model.manufacturer_id = manufacturer.manufacturer_id and manufacturer.manufacturer_name = 'ford'
My relations are as follows:
Manufacturers
| 2 | toyota |
Models
| 3 | 2 | corolla |
My classes are as follows:
Class Model extends Eloquent {
protected $table = ‘models’;
protected $primaryKey = 'model_id';
protected $guarded = array('model_id');
protected $fillable = array('manufacturer_id’,'model_name');
public function relatedtoManufacturer(){
return $this->belongsTo(‘Manufacturer’,'manufacturer_id');
}
}
Class Manufacturer extends Eloquent {
protected $table = ‘manufacturers’;
protected $primaryKey = 'manufacturer_id';
protected $guarded = array('manufacturer_id');
protected $fillable = array('manufacturer_name');
public function relatedtoModel(){
return $this->belongsToMany(‘Model’,'manufacturer_id')
}
}
Any help would be appreciated! Thanks!
you use first
because the query will return an array
Manufacturer::where( 'name', 'Ford' )->first()->models;
if you know the id
, better yet
Manufacturer::find( 1 )->models;
Wow thank you so much!
For anyone else out there with a similar issue here is my final as I had some mistakes/typos in my classes:
$models = Manufacturer::where( 'manufacturer_name', 'ford' )->first()->relatedtoModel;
Class Manufacturer extends Eloquent {
protected $table = 'manufacturers';
protected $primaryKey = 'manufacturer_id';
protected $guarded = array('manufacturer_id');
protected $fillable = array('manufacturer_name');
public function relatedtoModel(){
return $this->hasMany('Model','manufacturer_id');
}
}
Class Model extends Eloquent {
protected $table = 'models';
protected $primaryKey = 'model_id';
protected $guarded = array('model_id');
protected $fillable = array('manufacturer_id','model_name');
public function relatedtoManufacturer(){
return $this->belongsTo('Manufacturer','manufacturer_id');
}
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community