I'm having trouble figuring out how to access a nested relationship within Laravel. The specific example I have is a Movie that has many entires in my Cast table which has one entry in my People table. These are my models:
MOVIE
class Movie extends Eloquent {
protected $primaryKey = 'movie_id';
protected $table = 'movie';
// Relationships
public function cast()
{
return $this->hasMany('MovieCast', 'movie_id');
}
}
MOVIECAST
class MovieCast extends Eloquent {
protected $table = 'movie_cast';
public function person()
{
return $this->hasOne('Person', 'person_id');
}
public function netflix()
{
return $this->belongsTo('Movie', 'movie_id');
}
}
PERSON
class Person extends Eloquent {
protected $primaryKey = 'person_id';
protected $table = 'people';
public function movieCast()
{
return $this->belongsTo('MovieCast', 'person_id');
}
}
In my controller I can access the cast (containing person_id and role_id) like so:
public function movie($id)
{
$movie = Movie::find($id);
$cast = $movie->cast();
return View::make('movie')->with(array(
'movie' => $movie,
'cast' => $cast
));
}
...but I don't know how to access the corresponding name field in my People table.
EDIT 1:
Using the classes exactly as defined below in #msturdy's answer, with the controller method above I try to render the person names like so inside my view:
#foreach($cast->person as $cast_member)
{{$cast_member->person->name}}
#endforeach
Doing this i get the error:
Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$person
I don't know if it makes a difference or not but I have no id field on my People table. person_id is the primary key.
It should be simple, once you have accessed the cast...
Route::get('movies', function()
{
$movie = Movie::find(1);
$cast = $movie->cast;
return View::make('movies')->with(array(
'movie' => $movie,
'cast' => $cast));
});
Note: at this point, $cast is an instance of the Collection class, not a single object of the MovieCast class, as the
relationship is defined with hasMany()
you can iterate over it in the View (in my case /app/views/movies.blade.php
#foreach($cast as $cast_member)
<p>{{ $cast_member->person->name }}</p>
#endforeach
Class definitions used for testing:
class Movie extends Eloquent {
protected $primaryKey = 'movie_id';
protected $table = 'movie';
public $timestamps = false;
// Relationships
public function cast()
{
return $this->hasMany('MovieCast', 'movie_id');
}
}
class MovieCast extends Eloquent {
protected $table = 'movie_cast';
public $timestamps = false;
public function person()
{
return $this->hasOne('Person', 'person_id');
}
}
class Person extends Eloquent {
protected $primaryKey = 'person_id';
protected $table = 'people';
public $timestamps = false;
public function movieCast()
{
return $this->belongsTo('MovieCast', 'person_id');
}
}
Related
I'm trying to retrieve data from many to many relationship.I have two tables :
companies: [cid,name,origin]
vehicle_types: [id, type]
their pivot table: companies_vehicle_types: companies_id,vehicle_types_id Relationship defined: In Companies:
class companies extends Model
{
//
protected $fillable = ['name','origin'];
protected $primaryKey = 'cid';
public function vehicles(){
return $this->hasOne('App\vehicles');
}
public function vehicle_types(){
return $this->belongsToMany('App\vehicle_types', 'companies_vehicle_types', 'companies_id', 'vehicle_types_id');
}
}
In vehicle_types
class vehicle_types extends Model
{
//
protected $fillable = ['type'];
public function vehicles(){
return $this->belongsTo('App\vehicles');
}
public function companies(){
return $this->belongsToMany('App\companies','companies_vehicle_types','vehicle_types_id','companies_id')->withTimestamps();
}
}
I want to retrieve companies where vehicle_types = specific type. How can i do that? I tried doing following in my controller:
$vehicle_types=vehicle_types::where('type','Bike')->get();
foreach ($vehicle_types as $vehicle_type) {
# code...
foreach ($vehicle_type->companies as $company) {
$brand[]=$company->pivot->name;
}
}
return $brand;
But it doesn't seem to be working. $vehicle_types is working fine and returning value. $brand is not returning any value.
here is an example
Table Structure
Game
--id
--game
Posts
--id
--game_id
--post_text
class Posts extends Eloquent {
protected $primaryKey = 'id';
protected $table = 'posts';
public function games() {
return $this->hasOne('games','id');
}
}
class Games extends Eloquent {
protected $primaryKey = 'id';
protected $table = 'games';
public function posts() {
return $this->belongsTo('posts','game_id');
}
}
I need to get the game name of a certain post. How can I get it using eloquent?
here is my initial code
echo $post->games['game'];
but I get the wrong data.
The way it queries is this.
'query' => string 'select * from `games` where `games`.`id` = ? limit 1' (length=52)
'bindings' =>
array (size=1)
0 => int 5
Firstly Eloquent model names are not plural, so by default they should be Game and Post.
Secondly relationship return values must be changed. In hasOne and belongsTo you will need to use model class names like below. I also left out some optional code which is not required for the code to work.
class Post extends Eloquent {
public function game() {
return $this->hasOne('Game');
}
}
class Game extends Eloquent {
public function post() {
return $this->belongsTo('Post');
}
}
Now you can get the game name by $post->game->name
I have the following relations:
Discount:
<?php
class Discount extends Eloquent {
protected $table = 'discount';
public $timestamps = true;
public function title()
{
return $this->hasOne('Translation', 'labelId', 'titleLabelId')->where('languageId', T::getLang())->first()['phrase'];
}
public function titles()
{
return $this->hasMany('Translation', 'labelId', 'titleLabelId');
}
}
?>
Translation:
<?php
class Translation extends Eloquent {
protected $table = 'translations';
public $timestamps = false;
protected $fillable = array('phrase', 'languageId', 'labelId');
public function language()
{
return $this->belongsTo('Language', 'languageId');
}
public function label()
{
return $this->belongsTo('Label', 'labelId');
}
}
?>
Label:
<?php
class Label extends Eloquent {
protected $table = 'label';
public $timestamps = false;
protected $fillable = array('key');
public function translations()
{
return $this->hasMany('Translation', 'labelId', 'id');
}
}
?>
There are three database tables with the following columns:
Discount:
id | titleLabelId
Translation:
id | languageId | labelId
Label:
id
The problem: I'd like to create a title (translation) and associate it with the discount. Here's what I've tried:
$discount = new Discount;
/*create a new label*/
$labelKey = Label::max('key') + 1;
$label = new Label(array('key' => $labelKey));
$label->save();
/*create a new title (and associate it with the label)*/
$title = new Translation(
array(
'phrase' => $input['title'],
'languageId' => 3,
'labelId' => $label->id
));
$title->save();
$discount->save();
$discount->titles()->save($title);
Apparently, the $discount->titles()->save($title); part doesn't work. The title is only attached to the discount if I do it manually: $discount->titleLabelId = $label->id. Is there a way to do it using the ORM?
In your Discount Model, do you have your relationship set up to use the proper table and foreign key?
class Discount extends Eloquent
{
public function titles()
{
return $this->belongsTo('Translation', 'translations', 'titleLabelId');
}
}
When trying to associate one model with another through a defined relationship in Eloquent, you should use the associate() method rather than the save() method.
$discount->titles()->associate($title);
Before this happens though, you should be sure to call the save() method on anything that has been altered or is new.
So I have three models and when when one of them dAgency is deleted delete-() I'd like all three to be deleted. The problem is that two of them are being deleted, while the top parent one DemDataSet isn't being deleted. Additionally, when I call:
echo "<pre>", dd(dAgency::find(21)->DemographicReport()->DemDataSet()->get()), "</pre>";
I get this error: Call to undefined method Illuminate\Database\Query\Builder::DemDataSet() But when I try:
echo "<pre>", dd(dAgency::find(21)->DemographicReport()->get()), "</pre>";
It works. So I know the problem is my relation between my DemDataSet model. Below is my model:
<?php
class DemDataSet extends Eloquent {
public $timestamps = false;
protected $connection = 'epcr_dem_data';
protected $table = 'DEMDataSet';
protected $primaryKey = 'pk_DEMDataSet';
public function DemographicReport(){
return $this->hasOne('DemographicReport','fk_DEMDataSet','pk_DEMDataSet');
}
}
class DemographicReport extends Eloquent {
public $timestamps = false;
protected $connection = 'epcr_dem_data';
protected $table = 'DemographicReport';
protected $primaryKey = 'pk_DemographicReport';
public function DemDataSet (){
return $this->belongsTo('DemDataSet','fk_DEMDataSet','pk_DEMDataSet');
}
public function dAgency(){
return $this->hasOne('dAgency','fk_DemographicReport','pk_DemographicReport');
}
public function delete(){
parent::delete();
return $this->DemDataSet()->delete();
}
}
class dAgency extends Eloquent {
public $timestamps = false;
protected $connection = 'epcr_dem_data';
protected $table = 'dAgency';
protected $primaryKey = 'pk_dAgency';
public function DemographicReport(){
return $this->belongsTo('DemographicReport','fk_DemographicReport','pk_DemographicReport');
}
public function dAgency_10(){
return $this->hasMany('dAgency_10','fk_dAgency','pk_dAgency');
}
public function delete(){
parent::delete();
return $this->DemographicReport->delete();
}
}
?>
I've been wrestling with this one for two days now! I really appreciate you taking the time to look at this.
The right way to query laravel model with relationship is this way:
//This is to pull all DemDataSet from DemographicReport
dAgency::find(21)->DemographicReport()->first()->DemDataSet;
//If you need further query, then you call DemDataSet as a method
dAgency::find(21)->DemographicReport()->first()->DemDataSet()->where('your condition here')->get();
I have a laravel model
class Project extends Eloquent {
public static $timestamps = true;
public $includes = array('members','members.memberdata');
public function tasks() {
return $this->has_many('Usertask','project_id');
}
public function members() {
return $this->has_many('Projectmember','project_id');
}
}
and a related models
class Projectmember extends Eloquent {
public static $table = "project_members";
public static $timestamps = true;
public function project() {
return $this->belongs_to('Project');
}
public function memberdata() {
return $this->has_one('Usermetadata','user_id');
}
}
class Usermetadata extends Eloquent {
public static $table = "users_metadata";
public function user() {
return $this->belongs_to('User');
}
public function member() {
return $this->belongs_to('Projectmember','user_id');
}
}
When i attempt to retrieve a single project model like so
$project = Project::find($id);
return Response::eloquent($project);
my json output looks like this
{"id":1,"user_id":1,"name":"UberWork","description":"Web based project management \/ task management app","target_date":"2013-11-15 00:00:00","budget":null,"status":0,"created_at":"2013-04-16 20:13:59","updated_at":"2013-04-16 20:13:59","members":[{"id":1,"project_id":1,"user_id":1,"created_at":"2013-04-16 20:13:59","updated_at":"2013-04-16 20:13:59","memberdata":{"user_id":1,"first_name":"Tamarakuro","last_name":"Foh","photo":"","company_name":null,"phone":null,"package":"free","subscription_start":"0000-00-00 00:00:00","subscription_end":"0000-00-00 00:00:00","api_key":"12b14a7d3ca48c53bb5b1a88fa3eca3b"}},{"id":3,"project_id":1,"user_id":3,"created_at":"2013-04-16 20:13:59","updated_at":"2013-04-16 20:13:59","memberdata":{"user_id":3,"first_name":"Ebere","last_name":"Uche","photo":"","company_name":"Chronotech Labs","phone":null,"package":"free","subscription_start":"0000-00-00 00:00:00","subscription_end":"0000-00-00 00:00:00","api_key":"ab446bd9ffbb898e818a892c7401e0f6"}},{"id":4,"project_id":1,"user_id":2,"created_at":"2013-04-17 08:13:00","updated_at":"2013-04-17 08:13:00","memberdata":null}]}
My database look like this;
Users
id
email
password
ip_address
active
...
users_metadata
id
user_id
first_name
last_name
profile_photo
...
Projects
id
user_id
name
description
status
...
project_members
id
project_id
user_id
My question is why is the last member of the project having its memberdata as "null", while the others are not null. Am i doing something wrong?
Relationships in Eloquent always link a primary key (pk) with a foreign key (fk). However, you're trying to base a relationship on two foreign keys, skipping out a relationship. The only Eloquent solution is to include the extra relationship step. Here are some models (I've ommited the relationships we don't need for this example)...
class Project extends Eloquent {
public static $timestamps = true;
public $includes = array('members','members.user', 'members.user.metadata');
public function members()
{
return $this->has_many('Projectmember','project_id');
}
}
class Projectmember extends Eloquent {
public static $table = "project_members";
public static $timestamps = true;
public function user()
{
return $this->belongs_to('User');
}
}
class User extends Eloquent {
public static $timestamps = true;
public $hidden = array('password', 'ip_address');
public function metadata()
{
return $this->has_one('Usermetadata');
}
}
class Usermetadata extends Eloquent {
public static $table = "users_metadata";
public function user() {
return $this->belongs_to('User');
}
}
I can see why you'd want to skip the relationship, but sadly it's not possible with relationships.