i want to ask for laravel espcially infyom models generated - php

I try to use scaffold from table of relational-object database using infyom but i can't manipulate object like in POO because the models generated contains only the id of the other object! there is a way to manipulate object correctly?
model generated is like:
<?php
namespace App\Models;
use Eloquent as Model;
/**
* Class Facture
* #package App\Models
* #version July 17, 2018, 6:08 pm UTC
*
* #property \Illuminate\Database\Eloquent\Collection Consomme
* #property \Illuminate\Database\Eloquent\Collection contient
* #property \Illuminate\Database\Eloquent\Collection EstFactureBst
* #property \App\Models\EstFacture estFacture
* #property string num_facture
* #property date date_facture
* #property string etat_facture
* #property integer num_releve
*/
class personnel extends Model
{
public $table = 'personnel';
public $timestamps = false;
public $sousPersonnel;
protected $primaryKey = 'id_pers';
public $fillable = [
'id_pers',
'lib_pers'
];
/**
* The attributes that should be casted to native types.
*
* #var array
*/
protected $casts = [
'lib_pers' => 'string'
];
/**
* Validation rules
*
* #var array
*/
public static $rules = [
];
public function SousPersonnel(){
return $this->hasMany(\App\Models\TypePersonne::class);
}
}
there is a relation between my class personnel and TypePErsonne but when I want to write like $personnel->typePersonne and make dd I have it null I use Eloquent ORM it seems like they can't find typePersonne for my object $personnel

You have defined relation within the method named SousPersonnel() so to read it you should use SousPersonnel attribute like this:
$personnel->SousPersonnel

Related

PhpDOC syntax for related table

PHPStorm complains about a property accessed via magic method, because I didn't set the related comment:
<?php
namespace App\Controller;
use App\Model\Entity\ItemOrder;
use Cake\Datasource\Exception\RecordNotFoundException;
use Cake\Datasource\ResultSetInterface;
use Cake\Http\Response;
use Cake\Network\Exception\NotFoundException;
/**
* Items Controller
*
* #property ItemsTable $Items
*
* #method Item[]|ResultSetInterface paginate($object = null, array $settings = [])
*/
class ItemOrdersController extends AppController
{
/**
* Index method
*
* #return Response|void
*/
public function index()
{
$this->paginate = [
'contain' => ['Orders', 'ItemOrdersTypes', 'Products', 'ItemOrdersStates', 'Proformas', 'DeliveryNotes', 'Invoices']
];
$itemOrders = $this->paginate($this->Items);
$this->set(compact('itemOrders'));
}
/**
* Add method
* #param string $id Item id.
* #return Response|null Redirects on successful add, renders view otherwise.
*/
public function add($id)
{
$itemOrder = $this->ItemOrders->newEntity(); // <--- this one
// ...
}
}
I'm not sure what is the right syntax to declare such a property.
I tried with
* #property ItemOrders $ItemOrders
and
* #property ItemOrdersTable $ItemOrders
and
* #property object $ItemOrders
but without luck.
I also checked the docs for property and type without finding nothing useful.

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 5.1 suggested relationship setup

I am building a timesheet system and have setup a model for timesheets. Timesheet can have many rows - for example when I add a timesheet, I can add many days (rows) to the timesheet.
I want to be able to sync rows when a timesheet gets saved. For example, new rows will be added to the database, missing rows from the given array will be removed from the database.
I understand I can use sync method which works like this, however, I do not think I need a belongsToMany relationship. Currently I have my row relationship setup as a hasMany. The timesheet model looks like this:
<?php
namespace App\Models\Timesheet;
use Illuminate\Database\Eloquent\Model;
class Timesheet extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'timesheet';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['user_id', 'week', 'year', 'token', 'total_hours'];
/**
* Define that we want to include timestamps.
*
* #var boolean
*/
public $timestamps = true;
/**
* Boot the model.
*
*/
public static function boot()
{
parent::boot();
static::deleting(function($timesheet)
{
$timesheet->row()->delete();
});
}
/**
* The rows that belong to the timesheet.
*
* #return Object
*/
public function row()
{
return $this->hasMany('App\Models\Timesheet\RowTimesheet');
}
}
The row_timesheet model looks like this:
namespace App\Models\Timesheet;
use Illuminate\Database\Eloquent\Model;
class RowTimesheet extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'row_timesheet';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['timesheet_id', 'activity_category', 'description', 'eri_number', 'ewn_number'];
/**
* Define that we want to include timestamps.
*
* #var boolean
*/
public $timestamps = true;
What do I need to do in order to make something like this work:
$this->timesheet->find($id)->row()->sync($data);
Thanks in advance.
I believe the 'sync' methods works with 'belongsTomany' relationship.
what you have is 'hasMany' relationship, for that you need to do something like below
use 'save' method instead of 'sync' for hasMany relationship
$data = new App\Comment(['message' => 'A new comment.']);
$this->timesheet->find($id)->row()->save($data); // saves single row sheet object for a timesheet
$this->timesheet->find($id)->row()->saveMany($multipleData); // saves multiple row sheet objects for a timesheet

Laravel PHP: Creating default object from empty value error

I'm using a controller to call up a form defined in one of my views. Within the controller, I have a simple 'create()' method that I just want to use to call up a form while using the 'Video' model I've defined. The problem is when I try to call this function, I keep getting a 'Creating default object from empty value' error.
Controller(app\VideosController.php):
<?php
use Acme\repositories\VideoRepository;
use Models\Video;
use Models\Validators as Validators;
class VideosController extends BaseController {
/**
* The video model
*
* #var \Models\Video
**/
protected $video;
/* The value defined from my repository
*/
protected $videoRepo;
/**
* Instantiate the controller
*
* #param Models\Video $video
* #return void
**/
public function __construct(VideoRepository $videoRepo)
{
$this->videoRepo = $videoRepo;
/* Old code below
$this->video = \App::make('Repositories\VideoRepository');
*/
}
/* Create a new video by passing in a sub view
Of the form for creating a new video */
public function create()
{
$data = array('type' => 'video');
$this->layout->content = \View::make('forms.new-video', $data);
}
}
Model(app/models/video.php):
<?php
class Video extends Eloquent {
/**
* The table used by this model
*
* #var string
**/
protected $table = 'videos';
/**
* The primary key
*
* #var string
**/
protected $primaryKey = 'video_id';
/**
* The fields that are guarded cannot be mass assigned
*
* #var array
**/
protected $guarded = array();
/**
* Enabling soft deleting
*
* #var boolean
**/
protected $softDelete = true;
}
The view for my form is located at 'app\views\forms\new-video.blade.php'.
Am I not defining my 'create()' method properly or is a matter of not placing files in their correct location?
I believe you are missing the declaration of the $layout property in your controller, so it has no idea what view to use as the template:
/**
* The layout that should be used for responses.
*/
protected $layout = 'layouts.master';
See http://laravel.com/docs/4.2/templates#controller-layouts.

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)

Categories