I have a relationship many to many table progvol, table users, table flights
And a one-to-many table users relation rammasage
In the table rammassage I have a date field and in the table flights I have a start date I ve compare these two dates
So I write a sql query to know the date of the user of the vol table.
First j fai ds my controller to get the current user $ user = $ this-> getUser ();
And in my repositroy i did
<?php
namespace PfeBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* programmevolRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class programmevolRepository extends EntityRepository
{
public function getOnlyActive ($valeur,$vol)
{
$qb = $this->createQueryBuilder('a');
$qb->where('a.users = :valeur'); // means id_user of table programmevol = $valeur($user->getId());
$qb->where('a.vols = :vol'); // means id_vol of table vol = $vol (une instancedelaclassevol->getId());
$qb->where('vol' , $vol);
$qb->setParameter('valeur', $valeur);
return $qb->getQuery()->getOneOrNullResult();
}
}
in My controller i did
$comp = new CompanyEvents();
$user = $this->get('security.token_storage')->getToken()->getUser();
$userprogvol = $em->getRepository('PfeBundle:programmevol')->getOnlyActive($user->getId(),$comp->getId());
Now I have a $ userprogvol table in which I have the flight id of the programvol table + the id of the current user
Now I want to do (if $ userprog-> flights (id_vol) == $ comp-> id_vol) $ var = $ comp-> getDebt (); But $ userprogvol is an array ??
How can i do this please? Is there another trick (return type of a query is object) ??
well if it is an array you could just iterate it
foreach ($userprog->flights() as $flight) {
if($flight->getId() == $comp->getId()){
//...
}
}
because your variable and property naming is totaly unclear to me, this is just for let you get an idea
and it is not a simple array but an doctrine arrayCollection
so here you have a list of available methods
http://www.doctrine-project.org/api/common/2.3/class-Doctrine.Common.Collections.ArrayCollection.html
maybe $userprog->flights()->contains($element)
is what youre really after
Related
So I have a database setup like this.
Phone numbers belong to groupings. And users belong to groupings as well. I'm trying to figure out how to get all users that belong to a grouping but through the entity object instead of just a query if this is possible.
For example I'm aware I could do a query like this...
<?php
/**
* Auto generated by MySQL Workbench Schema Exporter.
* Version 3.0.3 (doctrine2-annotation) on 2017-03-27 04:09:37.
* Goto https://github.com/johmue/mysql-workbench-schema-exporter for more
* information.
*/
namespace Entity;
use Doctrine\ORM\Mapping as ORM;
use Entity\BaseGrouping;
/**
* Entity\Grouping
*
* #ORM\Entity()
*/
class Grouping extends BaseGrouping
{
public function getUsersByPriority(){
global $entityManager;
$users = $entityManager->getRepository('Entity\User')->findBy(array(),array('priority' => 'ASC'));
return $users;
}
}
With a little modification I could add another filter perhaps so that only the correct results pertaining to that group are shown instead of everything. Right now this will result in just every user showing instead of those that should belong to just the group.
What I'm looking for is something kind of like this...
$results = $entityManager->getRepository('entity\Phonenumber')->findBy(array('number' => '+'.$numberCalled));
if(count($results)<=0 || count($results)>1){
sendEmail('Error Occured', 'There was duplicate phone numbers in the database, used fallbacknumber<br/><br/>'.print_r($_REQUEST,true),"joe#poolserviceusa.com");
return $fallbacknumber;
}else{
$phonenumber = $results[0];
$group = $phonenumber->getGrouping(); //#JA - Returns the group object and stores it to variable group in scope
}
//Get list of all users in the group
$users = $group->getUsersByPriority(); //#JA - Returns all users associated with the group
//Find the first active and not busy user
foreach($users as $user){
echo '<test>'.$user->getUserName().'<test>';
}
Since I mapped correctly all the doctrine classes I'm able to just say $phonenumber->getGroupings(); and it returns me only the groupings that belong to that phonenumber which is perfect!
What I need now however is all the users that belong to that particular group?
Easy enough if we do $group->getUsers(); The problem here is I need the users sorted by priority and there is no sorting when I use these default methods.
How do I get all the users of just the group while sorting by priority?
I think I found the answer but I don't know if this is the best answer or not. I modified the function getUsersByPriority to this.
public function getUsersByPriority(){
global $entityManager;
$grouping_id = $this->getId();
$users = $entityManager->getRepository('Entity\User')->findBy(array('grouping_id' => $grouping_id),array('priority' => 'ASC'));
//#JA - Get reference to the users of just this grouping.
$users = $this->users;
return $users;
}
I didn't realize I could use $this->getId(); to get reference to the current instance in this case.
I have a field in my model Person called jobs that I'm casting as an array. jobs is an array of ids related to a Jobs table. I want to be able to query Person and return all that have a certain id in their jobs array. I see that Laravel has a whereIn clause which checks if a database value is in an array but I need the opposite - to check whether a database array contains a value.
Am I stuck having to use where('jobs', 'like', '%"' . $job_id . '"%')?
I'm not sure there's an opposite however if you're simply looking to make the query a bit more reusable, you could make it a local scope by adding this to your Person model:
/**
* Scope a query to only include persons with given job id.
*
* #return \Illuminate\Database\Eloquent\Builder
*/
public function scopeHasJob($query, $jobId)
{
return $query->where('jobs', 'like', "%\"{$jobId}\"%");
}
The name of the scope hasJob may interfere with the parent QueryBuilder method has so you might have to come up with a different name for it.
Now you can use Person::hasJob($job->id). However rather than storing the job ids in a column as an array, you should consider creating a pivot table to map the relationships between a person and job. You can do this using php artisan:
php artisan generate:pivot persons jobs
php artisan migrate
Then you need to add the relationship into your Person model:
/**
* The person's jobs
*/
public function jobs()
{
return $this->belongsToMany('App\Job');
}
So you can query your Person model by Job like this:
Person::whereHas('jobs', function ($query) {
return $query->whereId($job->id);
});
Laravel includes whereJsonContains(): So your field jobs that you
are casting as an array, that can query as :
->whereJsonContains('jobs', 3)
That way worked for me ...
I am adding a little more info to Zubayer Hossain's answer
The data types have to match:
// [1, 2]
->whereJsonContains('players', 1) // Works.
->whereJsonContains('players', '1') // Doesn't work.
// ["1", "2"]
->whereJsonContains('players', '1') // Works.
->whereJsonContains('players', 1) // Doesn't work.
whereJsonContains can be used in cases where we need to check if a value matches a json encoded field in our table.
Courtesy : https://newbedev.com/php-wherejsoncontains-and-with-laravel-example
You could use something like this query.
$k = ["359045532","359079612","359079372","359081292","359081052","359086332","359086092","359111892","359111652"];
Modal::whereIn('myitems', $k)->get();
<!-- If you have a collection of value like this: -->
$category_id = 1,2,3,...;
$category_id = $_POST['category_id'];
$myArray = explode(',', $category_id);
<!-- If you already have array data you can pass this to the following query -->
$data = DB::table('tablename')->select('*') ->whereIn('catcode', $myArray)->get();
Hello I am trying to access a value from a joined table schead.section to store in subjectcontainer.section, mainly I am using the scstock data but the section part is located in schead.section so what I did was to join the schead and schstock together so that I can have access to the section column. Here is what I did.
$subject = ActiveCurriculum::find()
->select('scstock.*')
->leftJoin('schead', 'schead.TrNo = scstock.TrNo')
->where([ 'schead.TrNo' => $TrNo])
->one();
$activesubject = new ActiveSubject();
$activesubject->clientid = $clientid;
$activesubject->TrNo = $subject->TrNo;
$activesubject->subjectcode = $subject->subjectcode;
$activesubject->schedday = $subject->schedday;
$activesubject->schedtime = $subject->schedtime;
$activesubject->section = $subject->section;
$activesubject->room = $subject->room;
$activesubject->units = $subject->units;
$activesubject->save();
//reduces the slot of ccsubject by 1
$subject->slots = $subject->slots - 1;
//never forget the saving part
$subject->save();
First $subject will access sctock table to join will schead via TrNo. then $activesubject will access subjectcontainer table to store the values in. Now my problem is I am getting this error.
Can someone help me in trying to solve this?
Make sure to define relation to the Schead object in your model. Example of such relation:
/**
* #property $schead Schead
*/
class YourModel extends \yii\db\ActiveRecord
{
/**
* #return Schead
*/
public function getSchead()
{
return $this->hasOne(Schead::className(), ['field1' => 'field2']);
}
}
Also, $subject->schead.section is a wrong way of accessing related model attributes. Use $subject->schead->section instead. If having schead is optional, don't forget to check existence of related object first, for example:
$subject->schead ? $subject->schead->section : null
Also check code for typos (probably sched / schead?). You can read more about working with relations in official docs.
I need to generate next number based on month and year. Is this proper way to do it or can it be done differently?
class Foo extends Model
{
public function getNextNumber()
{
$result = DB::select('SELECT COALESCE(MAX(number), 0) + 1 AS number FROM foo AS t2 WHERE MONTH(generated_at) = MONTH(CURDATE()) AND YEAR(generated_at) = YEAR(CURDATE())');
return head($result)->number;
}
}
When create a new record:
$foo = new Foo();
$foo->template = 'template1';
$foo->number = $foo->getNextNumber();
$foo->generated_at = DB::raw('NOW()');
$foo->save();
The query itself is fine as long as you don't have too many records in your table - otherwise I'd follow Joel's suggestion and store current number for given year and month in separate table like
Numbers(year, month, number).
If the Laravel code you provided is something you want to run for every model you create, so I'd suggest using Eloquent model events for that:
//Foo.php
protected static function boot() {
parent::boot();
static::creating(function($foo) {
$foo->number = $foo->getNextNumber();
$foo->generated_at = DB::raw('NOW()');
});
}
You could also make the getNextNumber method static so that you don't need an object to get the next number.
I have a very simply structured entity that contains a simple association
Database_Entity_Tenant
id (primary key)
parentId (id of the parent entry)
code (a simple identifier for the tenant, unique)
I defined parentId in my entity accordingly:
/**
* #Column(type="integer")
* #OneToOne(targetEntity="Tenant")
* #JoinColumn(name="parentTenantId", referencedColumnName="id")
* **/
protected $parentId;
This works fine - the generated database schema resembles my choices and its good.
Now i am writing my first method which basically has to return an array of all the tenants that are chained together, in reverse order (i use this for walking backward through a chain of tenants).
In order to do that i came up with the idea to use a while() loop.
$currentTenant = {DATABASE_ENTITY_TENANT}; // In my real code i fetch the entity object of the current tenant
$chain[] = $currentTenant;
$repository = Database::entityManager()->getRepository('Database_Entity_Tenant');
while(!$currentTenant->getParentId()){
$currentTenant = $repository->findOneBy(array(
'id' => $currentTenant->getParentId()
));
$chain[] = $currentTenant;
}
Any tenant that has no parent (such as the base tenant) will have no parent id (or null), so that would end the while loop.
Now all this may work, but it seems really rough to me. I am fairly new to Doctrine so i don't know much about it but i am sure there is some way to do this more elegantly.
QUESTION
Does Doctrine 2 provide me with any set of functions i could use to solve the above problem in a better way?
If not, then is there any other way to do this more elegantly?
If I'm not getting your problem wrong, you just need to find all the entries in your association table ordered by the parentId. In Doctrine2 you can do the following:
$currentTenant = {DATABASE_ENTITY_TENANT}; // assuming a valid entity
$repository = Database::entityManager()
->getRepository('Database_Entity_Tenant')
->createQueryBuilder('t')
->where('t.parentId IS NOT NULL')
->andWhere('t.parentId < :current') /* < or > */
->setParameter('current', $currentTenant->getParentId()->getId())
->orderBy('t.parentId', 'ASC') /* ASC or DESC, no array_reverse */
->getQuery()
->getResult();
/* At this point $repository contains all what you need because of Doctrine,
* but if you want a chain variable: */
$chain = array();
foreach ($repository as $tenant) {
$chain[] = $tenant->getCode(); // your tenant entity if your entity is mapped correctly
}
Hope this helps!