Laravel 4 Loading all songs from a playlist in database - php

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

Related

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

How to get department name of a module in Laravel models

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

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 One to many relation with custom primary key not working

I am trying to implement one to many relation in laravel
My tables have custom primary key name not id
I have set $primartKey attribute as well but the relations doesnot seem to work.
activities
|act_ID|act_acc_ID|.........
categories
|acc_ID|.......
Here are my Models
class Adventure extends \Eloquent {
/**
* #var string $table the name of the table
*/
protected $table = 'activities';
/**
* #var string $primaryKey the primary key of the table
*/
protected $primaryKey = 'act_ID';
/**
* #var bool timestamps updated_at and created_at columns flag
*/
public $timestamps = false;
/**
*
*/
public function category(){
$this->belongsTo('Category','act_acc_ID');
}
}
class Category extends \Eloquent {
/**
* #var string $table the name of the table
*/
protected $table = 'categories';
/**
* #var string $primaryKey the primary key of the table
*/
protected $primaryKey = 'acc_ID';
/**
* #var bool timestamps updated_at and created_at columns flag
*/
public $timestamps = false;
public function adventures(){
$this->hasMany('Adventure','act_acc_ID');
}
}
Now when ever i try to access categories from adventure or adventures from categories i get
Relationship method must return an object of type
Illuminate\Database\Eloquent\Relations\Relation
What am i doing wrong here ??
There are plenty adventures whose category is 15 so i try
I try Categories::find(15)->adventures also tried Categories::find(15)->adventures()
You didn't use return keyword, it should be something like this:
public function category(){
return $this->belongsTo('Category','act_acc_ID');
}
public function adventures(){
return $this->hasMany('Adventure','act_acc_ID');
}
Add the return keyword in both relationship methods.
you have to set this in you Category model
public $incrementing = false;

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