Make a variable with array of data from Laravel ManyToMany relationship - php

Im struggling to understand Laravels relationship usage. I finally managed to save the relationships between person and festival, using the model and this code:
$person = new Person;
$person->firstname = $firstname;
$person->lastname = $lastname;
$person->save();
$person_id = $person->id;
$person->festival()->attach($festival_id);
But I am not sure how to make a variable with all the persons of the festival im current working on. I store the value of festival_id in session:
$festival_id = Session::get('festival');
That is writing fine to my personFestival database.
id festival_id person_id
0 1 1
1 1 2
But i dont have any code in my PersonFestival-model, should I?
How can I retrieve all the persons of the festival with id=1 in a variable that I can use blade's foreach in a view on? Sorry about this mess, this is so confusing for me but i feel that im close to achieving it.
Tables:
persons (id, firstname, lastname)
festivals (id,name)
personFestival (id, person_id, festival_id)
Models:
class Festival extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $fillable = array(
'name','year','info','slug', 'image','created_by','updated_by'
);
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'fs_festivals';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function bands() {
return $this->hasMany('Band');
}
public function persons() {
return $this->belongsToMany('Person','fs_festival_persons','person_id','festival_id');
}
}
class Person extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $fillable = array(
'email','firstname','lastname','homepage', 'info','tlf','isonline','isbanned','username','password','password_temp','remember_token','code','active','created_by','updated_by'
);
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'fs_persons';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function festival() {
return $this->belongsToMany('PersonFestival','fs_festival_persons','person_id', 'festival_id');
}
}
class PersonFestival extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $fillable = array(
'person_id','festival_id'
);
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'fs_festival_persons';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}

Pivot tables (your fs_festival_persons table) don't usually have a model associated with them, unless you really need some special logic for them. In this case, it doesn't look like you do, so you can probably just get rid of that model.
To answer your other question, all of the persons associated with a festival can be accessed through the relationship on your festival model:
$festival = Festival::find(1);
// Collection of Person objects via lazy loading
$persons = $festival->persons;
// Relationship object:
$relation = $festival->persons();
// Manually getting the Persons through the relationship:
$persons = $festival->persons()->get();
// You can iterate the Collection just like an array:
foreach ($persons as $person) {
var_export($person->name);
}
You can read more on querying relationships here: Laravel 4.2 / Laravel 5.0

Related

How to query in terms of two columns in laravel eloquent orm

I need help to make a query in laravel.
I have three tables
1)Category(Contains id and name column).
2)Geometry(Contains id and name column).
3)practical(Contains id and name column and the Category_id,Geometry_id column/keys )
Now i want to search the practicals in terms of Category_id and Geometry_id.
The Practical.php model file is..
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Model;
use App\Models\Practical;
class Practical extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table='practical';
protected $fillable = [
'name',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
];
public function category()
{
return $this->belongsTo('App\Models\Category');
}
public function geometry()
{
return $this->belongsTo('App\Models\Geometry');
}
}
The Category and Geometry Model code is
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Model;
use App\Models\Geometry;
class Geometry extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table='geometry';
protected $fillable = [
'name',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
];
public function practical()
{
return $this->hasMany('App\Models\Practical');
}
}
I know how to query using only one ID.Category or geometry like this..
$Categories=Category::where('id',1)->firstOrFail();
but i failed to query by checking both the ids of Category and Geometry.
Now i want to search the practicals in terms of Category_id and Geometry_id
If you want to search practicals by category ID and geometry ID, just do a simple query:
Practical::where('category_id', $categoryId)
->where('geometry_id', $geometryId)
->get();

Join 2 tables in Eloquent Laravel 5.2 - How to retrieve all data from both two tables?

I have two tables
1.
Game Console
-- console_id
-- console_name
2.
Game Labels
-- game_label_id
-- console_id (foreign key)
-- title
-- description
-- image
-- created
GameConsole Model
namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;
class GameConsole extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
public $timestamps = false;
protected $table = 'console';
protected $fillable = array('console_name', 'description', 'created');
protected $primaryKey = 'console_id';
public function labels()
{
return $this->hasMany('App\Http\Models\GameLabel','console_id');
}
}
GameLabel Model
namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;
class GameLabel extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
public $timestamps = false;
protected $table = 'game_label';
protected $fillable = array('game_label_id','console_id', 'title','description','image', 'release_date','status','created');
protected $primaryKey = 'game_label_id';
public function console()
{
return $this->belongsTo('App\Http\Models\GameConsole','console_id');
}
}
I write this query to get all game labels with console_name
GameLabel::with('console')->get();
But I am only getting records from game_label table, not from console table.
Can any body please tell me that what query I have to write to get all records?
Please don't suggest me about query builder joins. I don't want to use that.
namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;
class GameLabel extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
public $timestamps = false;
protected $table = 'game_label';
protected $fillable = array('game_label_id','console_id', 'title','description','image', 'release_date','status','created');
protected $primaryKey = 'game_label_id';
public function console()
{
return $this->belongsTo('App\Http\Models\GameConsole', 'console_id', 'console_id');
}
}
in belongs to first console_id represent Game Console table id and and second console_id represent game_label table console_id
now in controller
GameLabel::with('console')->get();
i think all data will be availbale in array under console key
Yes, its under console key. I found the solution.
the console name was not getting in the view so get the console name in view like this
foreach($game_label as $getGameLabel){
echo $getGameLabel->console->console_name;
}

How to make HasMany Relation ship in Laravel 4.2

I have a user model looks like this
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function answer(){
return $this->hasMany('Answer','user_id');
}
public function supplierranking(){
return $this->hasMany('Supplierrank','userid','id');
}
}
Now each user will rank a company in a ranking Model which looks like this
Class Supplierrank extends Eloquent{
public function supplier(){
return $this->belongsTo('Supplier','supplierid','id');
}
public function user(){
return $this->belongsTo('User','userid','id');
}
}
I am able to get the user with the ranking details but I also have to get the details of companies that has been ranked from a Supplier table
which looks like this
Class Supplier extends Eloquent{
public function supplierranks(){
return $this->hasMany('Supplierrank','supplierid');
}
}
My query that I have done looks like this
$usersandranking = User::where('event','=',$exceleve)->with('supplierranking')->orderBy('id')->get();
It gets me user detail and there rankings but not the supplier names
Can any one help me on this

Laravel eloquent relationship not giving me what i want

im trying to figure out eloquent and having a hard time understand it, even tho ive tried to read up on it.
I have two tables: fs_festivals, and fs_bands.
fs_festivals: id, name
fs_bands: id, festival_id, name
So, one festival can have many bands, and one band belongs to a festival.
Band-model (Band.php)
class Band extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $fillable = array(
'festival_id','name','note','bandak', 'bandakinfo','created_by','updated_by'
);
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'fs_bands';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function festival() {
return $this->belongsTo('Festival');
}
}
Festival-model (Festival.php):
class Festival extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $fillable = array(
'name','year','info','slug', 'image','created_by','updated_by'
);
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'fs_festivals';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function bands() {
return $this->hasMany('Band');
}
}
In my controller:
public function festivalHome() {
$bands = Band::all();
return View::make('fis.festivalhome')->with('bands',$bands);
}
And in my view:
Bands:
#foreach($bands as $band)
{{ $band->name }}
#endforeach
This lists all bands in the fs_bands table. I only want to list those who are set with the festival_id of the current festival im working on (say festival_id='2'). How should i go about this?
Ive tried this (seeing what others have done),
#foreach($festival->$bands as $band)
But it gives me an error of
Undefined variable: festival
What am I doing wrong? Also I wonder, should I do something else instead of $bands = Band:all(); to list them by festival_id? That would be an option but something tells me that this should be done automatically with eloquent.
Controller:
public function festivalHome($id) {
//$bands = Band::all();
$festival = Festival::with('bands')->whereId($id)->first(); //it will load festival with all his bands
return View::make('fis.festivalhome')->with('festival',$festival);
// or you can filter bands
$bands = Band::whereHas('festival', function($query) use ($id){
$query->whereId($id);
})->get(); //there will be only bands which will be on the festival
}
And in your view:
#foreach($festival->bands as $band)
{{ $band->name }}
#endforeach
//or
#foreach($bands as $band)
{{ $band->name }}
#endforeach

Laravel: Trying to get relationship

User:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function email_preferences()
{
return $this->hasOne('EmailPreference');
}
}
EmailPreference:
class EmailPreference extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'email_preferences';
public function user()
{
return $this->belongsTo('User');
}
}
users table
id PK
first_name
last_name
email
email_preferences table
id PK
user_id FK (users.id)
newsletter
I'm trying to display the email preferences for a user:
$user = Auth::user();
echo '<pre>';
print_r($user->email_preferences);
exit;
I get nothing...
It sounds like you want something like this:
<?php
$user = Auth::user();
echo 'Receive newsletter? ' . ($user->emailPreferences->newsletter ? 'Yes' : 'No');
EDIT:
I did some digging & found that underscores can be tricky when used in Eloquent function/property names. If you eliminate the underscore, things should just work:
<?php
class User extends Eloquent implements UserInterface, RemindableInterface {
public function emailPreferences()
{
return $this->hasOne('EmailPreference');
}
}
See this answer: Laravel 4 Eloquent ORM accessing one-to-one relationship through dynamic properties

Categories