Accessing Doctrine related field from JOIN - php

I am attempting to pull a list of users using doctrine, with a join, from my database. I have the following function in my model:
public function getAttendees() {
$q = Doctrine_Query::create()
->select('a.id, a.name, a.url, m.id')
->from('Attendees a')
->leftJoin('a.Meetings m WITH m.Meeting_Slot_ID = ?', $this->getId());
return $q->execute();
}
I've checked the SQL generated by this query, and it is gabbing all the data I want. I am now trying to access the data retrieved. I have the following working:
foreach($object0>getAttendees() as $attendee){
echo $attendee->getName();
}
However, I can't figure out how to access the m.id field.

I think you can do this:
$attendee->getMeetings()->getId()
You have to use the alias you defined in your schema.yml (if you are using symfony)
Generally Doctrine uses this way to chain related models together:
model1->model2->model3
...->getModel2()->getModel3()->getModel3Field()

$attendee->getMeeting()->getId(); OR soemthing to that effect depending on how you have your relations/properties named.

Related

SQL select show table if not same value from another table (Laravel)

This is my query, I tried this query it works.
SELECT *
FROM conference_venue
WHERE id_venue NOT IN (SELECT id_venue FROM submission_data WHERE id_submission = 1);
i want to display data in conference_venue. but I don't want to display data whose id_venue is the same as the submission_data table (same as id_venue whose id_submission is mentioned).
I'm trying to make a query for the laravel version, but it's a blank white screen with no errors.
DB::table('conference_venue')
->whereNotIn('id_venue', function($q){
$q->select('id_venue')
->from('submission_data')
->where('id_submission', '=', 1);
})->select('*')->get();
This query works when I try it in sql query console but fails when I try it with Laravel query builder.
You can try this:
DB::table('conference_venue')
->select('*')
->whereRaw(
'conference_venue.id_venue NOT IN (SELECT submission_data.id_venue FROM submission_data WHERE id_submission = 1)'
);
Or better yet, create a Model for conference_venue and submission_data (ie: ConferenceVenue, SubmissionData) and you can add Eloquent relationships for ConferenceVenue and SubmissionData.
Eloquent relationships, which supports a variety of common
relationships (One To One, One To Many, Many To Many, etc.), are
defined as methods on your Eloquent model classes. Since relationships
also serve as powerful query builders, defining relationships as
methods provides powerful method chaining and querying capabilities.
Eloquent: Relationships
On you ConferenceVenue Class, you can add a method something similar to the following:
public function available() {
return this->hasMany(SubmissionData, 'id_venue')
->select('*') // You can also specify relevant columns ONLY
->whereRaw(
'conference_venue.id_venue NOT IN (SELECT submission_data.id_venue FROM submission_data WHERE id_submission = 1)'
);
}
Where you can use the relationship method as follows:
$available = ConferenceVenue::with('available')->get();

Issue with "where" in an associated query in Symfony 3

I'm trying to make a "search engine" for my app; the table I want to show, contains two fields which are associated to another tables.
I'm using this query:
Select work from WorkBundle:Work work
where work.client.name like '$search%'
Work, is associated with the tables "user" and "client", I have the associations correctly defined so I don't have to use the inner join statement, but I get the following error:
[Semantical Error] line 0, col 68 near 'nombre like 'fsdf%'': Error: Class WorkBundle\Entity\Work has no field or association named client.nombre
I don't know how to access to the "name" field which is on the "client" table.
Actually I can do the same by using a full inner join query and it works but I can't use it in my app.
I do not know for sure but it seems you cant use selectors like work.client.name. I think it based on doctrine uses "lazy" queries. So you must use table joins in this case.
So it should look smth like that
// work repository
public function findByKeyword($keyword)
{
$qb = $this->createQueryBuilder("w");
$result = $qb
->add('where', $qb->expr()->like("wc.name", ':keyword'))
->leftjoin("w.client", "wc") //or join or innerjoin depends of your case
->setParameters([
'keyword' => $keyword
])
->getQuery()
->getResult()
;
return $result;
}

How to get multi activerecord model with only 1 join query in Yii2?

For example:
Query
SELECT book.\*,author.* FROM book
INNER JOIN author ON author.id = book.author_id
WHERE book.id=1
Get model
$modelBook = Book::find()->innerJoin('author','author.id = book.author_id')->where(['book.id'=>1])->one();
$modelAuthor = Author::findOne(['id'=>$modelBook->author_id]);
The problem:
How can I get 2 activerecord model Book and Author with just only one mysql execute?
I know that we can use with() function, but it spend another query SELECT ...IN(...) to get second model, although we have sufficient data from join query
Is there a more effective solution ?
ActiveRecord are for model extendinng the ActiveRecord classe
You seems are using a query and not a "model" so i suggest you of use activeDataProvider.
You can refer the models managed by dataProvider using getModels() function
$provider = new SqlDataProvider([
......
]);
// returns an array of data rows
$models = $provider->getModels();
see this guide and reference for detail
http://www.yiiframework.com/doc-2.0/guide-output-data-providers.html
http://www.yiiframework.com/doc-2.0/yii-data-sqldataprovider.html
Try this :
With approach is not slower in case of performance.
$modelBook = Book::find()->with('YOUR_RELATION_NAME_HERE')->findByPK(id);

Loading Relational Data from Views in CodeIgniter

I am using CodeIgniter
I have two tables -
Company
int id ,
varchar name
Employee int id, varchar name , int company_id
I have a simple controller called Employees Controller
<?php
class Employees extends CI_Controller {
public function index()
{
----
----
$data['employees'] = $selected_employees;
$this->load->view('employees/index',$data);
}
}
This controller passes an array of Employees to the view .
So inside my view , I can freely use employees[4].name , employees[3].id etc
Now If I want to show the name of the Company of the employees , it seems the only way is the Controller should pass another array with the name of the companies to the view . Is there any better way to achieve this - so that the controller doesnt have to explicitly have to send the data ?
For eg - say I want to access employees[4].company.name
I have been spoilt by Rails . I used to take these for granted .
The best way to go about this is using a join statement in your SQL query. The SQL query would typically look something like the following:
SELECT * FROM Employee JOIN Company ON Employee.company_id = Company.id
However, CodeIgniter's active record class will help us to simplify this (see http://ellislab.com/codeigniter/user-guide/database/active_record.html). In your model, you could write your query like so:
$this->db->select('*');
$this->db->from('Employee');
$this->db->join('Company', 'Employee.company_id = Company.id');
$query = $this->db->get();
You can tweak this to select the exact data that you want like you would any SQL query:
$this->db->select('Employee.id, Employee.name, Employee.company_id, Company.name AS company_name');
You can also add left, right, outer, inner, left outer, or right outer as a third parameter to the $this->db->join() function to allow for left joins, right joins, etc.
I would recommend using the Active Record class when possible in your CodeIgniter applications. It will help keep your queries clean, organized, and readable.
Do a join on your model
public function get_ selected_employees(){
$this->db->select('Employee.*, Company.name as company_name');
$this->db->from('Employee');
$this->db->join('Company', 'Employee.company_id = Company.id');
return $this->db->get()->result();
}
To get the company name just do employees[4].company_name

Symfony2 - Custom Repository + Doctrine QueryBuilder = Errors?

I have written a custom query in a repository:
public function findProductDetails($filter = array(), $offset = 0, $limit = 0)
{
$query = $this->getEntityManager()
->createQuery('SELECT prod, comp, cat FROM PaulDemoBundle:Product prod JOIN prod.category cat JOIN prod.company comp WHERE prod.productName LIKE \'%'.$filter['freetext'].'%\' ');
$query->setFirstResult($offset);
$query->setMaxResults($limit);
return $query->getResult();
}
Now I am trying to add an ORDER BY into it, using the orderBy() part of the Doctrine Query Builder:
$query->orderBy('prod.productRef', 'ASC');
But I get errors when trying to run this:
Call to undefined method Doctrine\ORM\Query::orderBy()
So I added the following to the top of my repository, underneath the USE call for EntityRepository:
use Doctrine\ORM\Query;
But, no dice.
All documentation I have found simply shows the query being built using the $query->orderBy() method. No where in the Symfony2 documentation does it say how to set up your repo to work with the Doctrine Query Builder.
How on earth do I add the orderBy() method?
Am I even constructing my query properly? (Its based on the Symfony2 docs, but they are pretty poor tbh)
If you are not using the queryBuilder, you cannot use the methods applied to it. Either you do your query on your own, adding the ORDER BY to your Query like this:
->createQuery('SELECT prod, comp, cat FROM PaulDemoBundle:Product prod JOIN prod.category cat JOIN prod.company comp WHERE prod.productName LIKE \'%'.$filter['freetext'].'%\' ORDER BY prod.productRef ASC');
or you build your Query with the QueryBuilder:
$qb = $em->createQueryBuilder();
...
See here for the QueryBuilder and here for differences on createQuery and QueryBuilder.
If you use the QueryBuilder, the right method is addOrderBy

Categories