How to get department name of a module in Laravel models - php

I am trying to get the department that a module is part of in laravel like:
This is my Faculty class:
<?php
class Faculty extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'faculty';
public $timestamps = false;
/**
* Whitelisted model properties for mass assignment.
*
* #var array
*/
protected $primaryKey='facultyid';
protected $fillable = array('facultyname', 'facultyshort');
public function departments()
{
return $this->hasMany('Departments', 'facultyid');
}
}
This is my Departments class
<?php
class Departments extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'departments';
public $timestamps = false;
/**
* Whitelisted model properties for mass assignment.
*
* #var array
*/
protected $primaryKey='departmentid';
protected $foreignKey='facultyid';
protected $fillable = array('departmentname', 'departmenthead', 'facultyid');
public function modules()
{
return $this->hasMany('Modules', 'departmentid');
}
public function faculty()
{
return $this->belongsTo('Faculty', 'facultyid');
}
}
and finally this is my modules class:
<?php
class Modules extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'modules';
protected $foreignKey='departmentid';
public $timestamps = false;
/**
* Whitelisted model properties for mass assignment.
*
* #var array
*/
protected $primaryKey='mid';
protected $fillable = array('mfulltitle', 'mshorttitle', 'mcode',
'mcrn', 'mfieldofstudy', 'mcoordinator','mlevel',
'mcredits', 'melective', 'departmentid');
public function department()
{
return $this->belongsTo('Departments', 'departmentid');
}
public function classes()
{
return $this->hasMany('Classes', 'moduleid')->orderBy('classid', 'ASC');
}
}
I have tried doing something like this:
#foreach(Modules::where('melective', '=', 1)->get() as $mod)
{{$mod->mshorttitle}} belongs to department: {{ $mod->department->departmentname }}
#endforeach
But it does not work, does anyone have any idea on how to do this?
==============================
SOLUTION
After a bit of work i figured it out
in Department class i added the following function:
public function name()
{
return $this->departmentname;
}
and i changed the code to the following:
#foreach(Modules::where('melective', '=', 1)->get() as $mod)
{{$mod->mshorttitle}} belongs to department: {{ $mod->department->name() }}
#endforeach

Related

Specify selected columns in Eloquent model class rather than querybuilder

Whenever I use an eloquent model, it will select *, unless I specify it in a querybuilder object. However, I want to specify allowed fields in the class. This would be useful for ensuring the correct user level gets the details they are entitled to, so it property live with the class.
I want to be able to do it as a member variable, like $with:
/**
* #property mixed id
*/
class Attribute extends Model
{
protected $fillable = ["id", "business_id", "attribute_name"];
protected $with = ["attributeDetail", "business"];
protected $selectedFieldsThatMeanSelectStarDoesntHappen = ["id", "business_id", "attribute_name"];
}
So any query using the above class will do SELECT id, business_id, attribute_name whenever the class is used, and not SELECT *.
Does the above functionality exist? The closest I can get is with a global scope:
class Attribute extends Model
{
/**
* The "booted" method of the model.
*
* #return void
*/
protected static function booted()
{
static::addGlobalScope('selectFields', function (Builder $builder) {
$builder->select("id", "business_id", "attribute_name");
});
}
}
You can try it:
Create a new builder and a trait to use this new builder:
class BuilderWithSpecifiedColumns extends Builder
{
public $selectedColumns = [];
public function __construct(ConnectionInterface $connection, Grammar $grammar = null, Processor $processor = null, array $selectedColumns = ['*'])
{
parent::__construct($connection, $grammar, $processor);
$this->selectedColumns = $selectedColumns;
}
/**
* #param string[] $columns
* #return \Illuminate\Support\Collection
*/
public function get($columns = ['*'])
{
return parent::get($this->selectedColumns ? $this->selectedColumns : $columns);
}
}
trait HasSelectedColumns
{
protected function newBaseQueryBuilder()
{
$connection = $this->getConnection();
return new BuilderWithSpecifiedColumns(
$connection,
$connection->getQueryGrammar(),
$connection->getPostProcessor(),
$this->selectedFieldsThatMeanSelectStarDoesntHappen,
);
}
}
Use above trait
/**
* #property mixed id
*/
class Attribute extends Model
{
use HasSelectedColumns;
protected $fillable = ["id", "business_id", "attribute_name"];
protected $with = ["attributeDetail", "business"];
protected $selectedFieldsThatMeanSelectStarDoesntHappen = ["id", "business_id", "attribute_name"];
}

In Laravel 5.3 Eloquent how to retrieve 3rd table data with where condition

I have 3 Models(each associated with a table separately) which associated with each other I have attached the table structure below
Models are,
Doctor Model associated with doctor_profile_master
<?php
namespace App\TblModels;
use Illuminate\Database\Eloquent\Model;
class Doctor extends Model
{
/**
* #var string
*/
protected $table = 'DOCTOR_PROFILE_MASTER';
/**
* #var string
*/
protected $primaryKey = 'doctor_profile_master_id';
/**
* #var array
*/
protected $fillable = ['doctor_id', 'user_master_id', 'doctor_first_name', 'doctor_last_name', 'doctor_isactive'];
/**
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function hospitalDoctorAssociateMasters(){
return $this->hasMany('App\TblModels\HospitalDoctorAssociateMaster','doctor_profile_master_id');
}
}
HospitalDoctorAssociateMaster Model associated with hospital_doctor_associate_master
<?php
namespace App\TblModels;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
class HospitalDoctorAssociateMaster extends Model
{
/**
* #var string
*/
protected $table = 'HOSPITAL_DOCTOR_ASSOCIATE_MASTER';
/**
* #var string
*/
protected $primaryKey = 'hospital_doctor_associate_master_id';
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function doctor(){
return $this->belongsTo('App\TblModels\Doctor','doctor_profile_master_id');
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function hospital(){
return $this->belongsTo('App\TblModels\Hospital','hospital_profile_master_id');
}
}
HospitalDoctorRecurringSchedule Model associated with hospital_doctor_recurring_schedule
<?php
namespace App\TblModels;
use Illuminate\Database\Eloquent\Model;
class HospitalDoctorRecurringSchedule extends Model
{
/**
* #var string
*/
protected $table = 'HOSPITAL_DOCTOR_RECURRING_SCH_MASTER';
/**
* #var string
*/
protected $primaryKey = 'hospital_doctor_recurring_sch_master_id';
public function hospitalDoctorAssociateMaster(){
return $this->belongsTo('App\TblModels\HospitalDoctorAssociateMaster','hospital_doctor_associate_master_id');
}
}
Thing i want to do is,
How to retrieve the hospital_doctor_recurring_sch_master table data using specific doctor_id(doctor_profile_master)
I tried some methods but cant able to retrieve those values.
Thanks in advance.
You could use something like this:
$hospitalDoctors = HospitalDoctorRecurringSchedule::with(['hospitalDoctorAssociateMaster', 'hospitalDoctorAssociateMaster.doctor', 'hospitalDoctorAssociateMaster.hospital'])->all();
To search by fields in related tables:
$hospitalDoctors = HospitalDoctorRecurringSchedule::with([
'hospitalDoctorAssociateMaster',
'hospitalDoctorAssociateMaster.doctor',
'hospitalDoctorAssociateMaster.hospital'])
->whereHas('hospitalDoctorAssociateMaster.doctor', function ($query) use ($doctorId) {
$query->where('doctor_id', '=', $doctorId);
})
->all();
For hospitalDoctorAssociateMaster.hospital:
Define Hospital Model and try

Laravel 4 Loading all songs from a playlist in database

Hey guys like explained in the heading I'm having a bit of trouble with Laravel,
I'm creating a system that a user can have various playlists (up to 5) and in each playlist is able to have a lot of songs (up to 50). I am trying to incorporate all this into this and trying to print it out as follows:
I have the following Class for Playlists:
<!-- language: lang-php -->
<?php
class Playlist extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'playlists';
public $timestamps = false;
/**
* Whitelisted model properties for mass assignment.
*
* #var array
*/
protected $primaryKey='playlistid';
protected $fillable = array('playlistname', 'userid');
public function songs()
{
return $this->hasMany('Song', 'playlistid');
}
}
And the following class for a song:
<?php
class Song extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $primaryKey='songid';
protected $foreignKey='playlistid';
protected $table = 'songs';
public $timestamps = false;
protected $fillable = array('songname', 'songurl', 'playlistid', 'position');
public function playlistid()
{
return $this->belongsTo('Playlist', 'playlistid');
}
public function fromList($id)
{
return $this->where('playlistid', $id);
}
}
And then I am trying to call it in my homepage like:
#foreach (Song::find(1)->fromList(1) as $song)
echo $song->songname
#endif
But it doesn't seem to be working, does anyone know a better way to do this or a fix?
Not sure if this is what you want, but here's how you print all the songs of one playlist:
#foreach(Playlist::find(1)->songs as $song)
{{ $song->songname }}
#endforeach

Eloquent multiple nested relations with constraint

Trying to get data from multiple nested relationship with a where constraint:
Model User:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
use Illuminate\Database\Eloquent\SoftDeletingTrait;
use Zizaco\Entrust\HasRole;
class User extends BaseModel implements UserInterface, RemindableInterface {
use HasRole;
protected $fillable = array('username', 'password');
/**
* 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');
protected $dates = ['deleted_at'];
protected $softDelete = true;
public function editor()
{
return $this->hasOne('User_Editor', 'user_id');
}
?>
Model User_Editor:
<?php
class User_Editor extends BaseModel {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users_editors';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array();
/**
* Defiens the column names of fillable columns.
*
* #var array
*/
protected $fillable = array();
/**
* Relationships
*/
public function credentials()
{
return $this->hasMany('User_Editor_Credential', 'user_editor_id');
}
public function specialties()
{
return $this->hasMany('User_Editor_Specialty', 'user_editor_id');
}
?>
Model User_Editor_Credentials:
<?php
class User_Editor_Credential extends BaseModel {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users_editors_credentials';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array();
/**
* Defiens the column names of fillable columns.
*
* #var array
*/
protected $fillable = array();
}
Model User_Editor_Specialties:
<?php
class User_Editor_Specialty extends BaseModel {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users_editors_specialties';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array();
/**
* Defiens the column names of fillable columns.
*
* #var array
*/
protected $fillable = array();
}
Return
select * from User, User_Editor, User_Editor_Credentials, User_Editor_Specialty where User_Editor_Specialty.specialty In (array).
So far I've tried,
$this->data['editors'] = User::with(['editor.credentials.specialties' => function($q) use($data){
$q->whereIn('specialty',$data);
}])
->get();
But this throws an error call to undefined method specialties. Please guide, thanks.
To those who might have suffered for long trying to find a way to work around nested relationships, and also, if you are writing a join condition with whereIn (which throws call to undefined method because of a bug in the Laravel), Please find below ans,
$editors = User::with(['editor.credentials','editor.specialties']);
$this->data['editors'] = $editors->whereHas('editor', function($q) use ($a_data){
$q->whereHas('specialties',function($sq) use($a_data){
$sq->whereIn('specialty',$a_data);
});
})->get();
Update: the PR has been just merged to 4.2, so now it's possible to use dot nested notation in has methods ( ->has('relation1.relation2) ->whereHas('relation1.relation2, .. )
Your dot notated relations must be logically chained:
`with(['editor.credentials', ' editor.specialties' => function ....
You tried to search for the specialties relation on the User_Editor_Credential model.
According to the comments:
User::with(['editor.credentials','editor.specialties'])
->whereHas('editor' => function($q) use ($data){
$q->whereHas('specialties' => function($q) use ($data){
$q->whereIn('specialty',$data);
});
})->get();
or if you use my PR https://github.com/laravel/framework/pull/4954
User::with(['editor.credentials','editor.specialties'])
->whereHas('editor.specialties' => function($q) use ($data){
$q->whereIn('specialty',$data);
})->get();
It will return all the users that have related editor.specialties matching whereIn, with related editor and all its related credentials and specialties (the latter won't be filtered)

laravel 4 pivot table save not working

I am having trouble saving(creating new row) with extra data to a pivot table.
I am having to use a legacy db schema (that is still working on a live site). I am currently redoing the site in Laravel.
<?php namespace Carepilot\Repositories\Organizations;
use Carepilot\Repositories\EloquentRepositoryAbstract;
/*
* This class is the Eloquent Implementation of the Organization Repository
*/
class OrganizationRepositoryEloquent extends EloquentRepositoryAbstract implements OrganizationRepositoryInterface {
/*
* Define Eloquent Organization Type Relation.
*
*/
public function orgtypes()
{
return $this->belongsToMany('Carepilot\Repositories\OrganizationTypes\OrganizationTypesRepositoryEloquent', 'organizations_orgtypes', 'organization_id', 'orgtype_id')
->withPivot('objectstate_id');
}
}
<?php namespace Carepilot\Repositories\OrganizationTypes;
use Carepilot\Repositories\EloquentRepositoryAbstract;
/*
* This class is the Eloquent Implementation of the Organization Repository
*/
class OrganizationTypesRepositoryEloquent extends EloquentRepositoryAbstract implements OrganizationTypesRepositoryInterface {
protected $table = 'orgtypes';
/*
* Define Eloquent Organization Type Relation.
*
*/
public function organizations()
{
return $this->belongsToMany('Carepilot\Repositories\Organizations\OrganizationRepositoryEloquent', 'organizations_orgtypes', 'organization_id', 'orgtype_id')
->withPivot('objectstate_id');
}
}
Here in the Orgaizations controller I try to save a new organization but get an error in the pivot table.
<?php
use \Carepilot\Repositories\Organizations\OrganizationRepositoryInterface;
use \Carepilot\Repositories\Procedures\ProcedureRepositoryInterface;
use \Carepilot\Helpers\StatesHelper;
class OrganizationsController extends BaseController {
/**
* Organization Repository
*
* #var organization_repo
*/
protected $organization_repo;
protected $procedures;
protected $states;
public function __construct(OrganizationRepositoryInterface $organization_repo,
ProcedureRepositoryInterface $procedures,
StatesHelper $states)
{
$this->organization_repo = $organization_repo;
$this->procedures = $procedures;
$this->states = $states;
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
return View::make('organizations.index');
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$supportedStates = ['' => 'Choose'] + $this->states->supportedStates();
$procedures = $this->procedures->getDropDown();
return View::make('organizations.create', compact('supportedStates', 'procedures'));
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$input = Input::all();
// validation here
$new_organization = $this->organization_repo->create(array_only($input, ['organization_name']));
$input['objectstate_id'] = 27;
$input['orgtype_id'] = 1;
$new_organization->orgtypes->pivot->create(array_only($input, ['objectstate_id', 'orgtype_id']));
$new_organization->addresses()->create(array_only($input, ['street1', 'zip', 'city', 'state_code']));
$input['objectstate_id'] = 4;
$new_organization->users()->create(array_only($input, ['first_name', 'last_name', 'email', 'password', 'objectstate_id']));
return "completed";
}
This returns "Undefined property: Illuminate\Database\Eloquent\Collection::$pivot” because the pivot has not been created yet. What am I missing?
I found that the 'attach' method does what I want with something like
$new_organization->orgtypes()->attach(1, ['objectstate_id' => '27']);

Categories