In laravel5 i belongsTo a model in a model that is
public function LeaveCategories()
{
return $this->belongsTo('App\LeaveCategories','leave_category_id','id');
}
Then i query in a controller that is
$userInfo = Leave::select(DB::raw('count(leaves.leave_category_id) as category_used'),
'LeaveCategories.id','LeaveCategories.category','LeaveCategories.category_num')
->where('Leaves.leave_date','>=', $first_day_this_year)
->where('Leaves.leave_date','<=', $last_day_this_year)
->where('Leaves.leave_status', 1)
->groupBy('Leaves.leave_category_id','LeaveCategories.category','LeaveCategories.category_num','LeaveCategories.id')
->get();
But it shows a error that is Unknown column 'LeaveCategories.id' in 'field list'
You use QueryBuilder, but belongsTo is ActiveRecord. Use that:
$userInfo = Leave::with('LeaveCategories')->where('Leaves.leave_date','>=', $first_day_this_year)
->where('Leaves.leave_date','<=', $last_day_this_year)
->where('Leaves.leave_status', 1)
->groupBy('Leaves.leave_category_id','LeaveCategories.category','LeaveCategories.category_num','LeaveCategories.id')
->get([DB::raw('count(leaves.leave_category_id) as category_used'),
'LeaveCategories.id','LeaveCategories.category','LeaveCategories.category_num']);
Related
I have the problem that the backend users can set a word with a "" character, for example something like "Test­ ;labor".
If someone uses the frontend search with the word "Testlabor" no match will be found.
In the extbase repository I used this:
$query->like('name', '%' . $searchWord . '%')
I can change that to something like this:
$query->statement("SELECT * FROM table WHERE hidden = 0 AND REPLACE(name,'', '') LIKE '%$searchWord%'")
Then the word will be found but I have to check all the things the framework normally does, like check if it's hidden and deleted and more complicated, if the result is in the right site tree. Now I just get everything that matches the searchword.
Is there a better way to search for words which have "" inside? Can I use something like that within the TYPO3 query builder?
Many thanks in advance.
You can try with QueryBuilder interface
public function findShy($searchWord)
{
/** #var ConnectionPool $pool */
$pool = GeneralUtility::makeInstance(ConnectionPool::class);
$connection = $pool->getConnectionForTable('table');
$queryBuilder = $connection->createQueryBuilder();
$query = $queryBuilder
->select('*')
->from('table')
->where("REPLACE(name,'', '') like :name")
->setParameter('name', "%{$searchWord}%");
// for debug only
echo($query->getSQL());
print_r($query->getParameters());
return $query->execute()->fetchAll();
}
and call it somewhere i.e. in your controller:
DebuggerUtility::var_dump(
$this->yourRepository->findShy('Testlabor'),
'findShy() sample'
);
it will create a query with named parameter like (according to your TCA of course):
SELECT *
FROM `table`
WHERE (REPLACE(name, '', '') like :name)
AND ((`table`.`deleted` = 0) AND (`table`.`hidden` = 0) AND
(`table`.`starttime` <= 1596363840) AND
((`table`.`endtime` = 0) OR (`table`.`endtime` > 1596363840)))
Note that returns associative array with the record not a mapped object of your model.
Optional
If you need mapped model objects anyway, you can mix these two solutions, i.e. first select only the pids of your records with QueryBuilder and then fetch them with Query which implements QueryInterface like this:
public function findShy2($searchWord)
{
/** #var ConnectionPool $pool */
$pool = GeneralUtility::makeInstance(ConnectionPool::class);
$connection = $pool->getConnectionForTable('table');
$queryBuilder = $connection->createQueryBuilder();
$preQuery = $queryBuilder
->select('uid')
->from('table')
->where("REPLACE(name,'', '') like :name")
->setParameter('name', "%{$searchWord}%");
// for debug only
echo($query->getSQL());
print_r($query->getParameters());
$uids = [];
foreach ($preQuery->execute()->fetchAll() as $item) {
$uids[] = $item['uid'];
}
if(count($uids) > 0){
$interfaceQuery = $this->createQuery();
$interfaceQuery->matching(
$interfaceQuery->in('uid', $uids)
);
return $interfaceQuery->execute();
}
return [];
}
UPDATE
My approach is to receive something equal to a simpel mysql join. I want all entries from tabel tx with project_id = x joined with txevent on tx.id = txevent.tx_id.
I´m using lumen 5.5
UPDATE 2
The following raw sql will do exactly what I want:
$rawTx = DB::>table('tx')
->join('txevent', 'txevent.tx_id', '=', 'tx.id')
->where('tx.project_id', $request->get('project_id'))
->where('txevent.short_id', $request->get('short_id'))
->get();
Isn´t it possible to achieve the same with relations?
END UPDATE
I´ve got 2 tables tx and txevent:
tx:
id, int, autoincrement
project_id, int
txevent:
id, int, autoincrement
tx_id, int, fk(tx.id)
shortnumber, char
in tx.php I´ve got the following method:
public function txeventWithShortnumber($shortnumber)
{
return $this->hasOne('App\Txevent')->where('shortnumber', $shortnumber)->first();
}
in TxController.php I´ll do:
$tx = Tx::where('project_id', $request->get('project_id'))->txeventWithShortnumber($request->get('shortnumber'))->get();
as result I get the following error message:
(1/1) BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::txeventWithShortnumber()
in Builder.php line 2483
Can someone tell me what I´m doing wrong?
I recommend to do it this way:
In Tx.php
public function txEvents()
{
return $this->hasMany(TxEvent::class);
}
public function txeventWithShortnumber($shortNumber)
{
return $this->txEvents->first(function($txevent) use ($shortNumber) {
return $txevent->shortnumber == $shortNumber;
});
}
In controller:
$tx = Tx::where('project_id', $request->get('project_id'))->get();
// attach shortNumber event
$tx->map(function($t) use ($request) {
$t->eventWithShortNumber = $t->txeventWithShortnumber($request->get('shortnumber'));
});
$tx variable will now hold txEvents with the given short number as well.
I am not sure if you can dynamically pass condition to an eloquent relationship.
Model:
public function fetch_emp()
{
$this->db->select('emp_id');
$this->db->from('emp');
$res=$this->db->get();
foreach($res->result() as $row)
{
$id=$row->emp_id;
$this->db->select('emp_name');
$this->db->from('employee_master');
$this->db->where('emp_id',$id);
$res=$this->db->get();
return $res->result();
}
}
Controller:
public function employee()
{
$result=$this->emp_model->fetch_emp();
if($result!=false)
$res['cmp_name']=$result;
else
$res['cmp_name']='NA';
}
$this->loadViews("emp/emp_views", $this->global, $res , NULL);
}
View:
<?php print_r($cmp_name);?>
Once I fetch the id from db I got all the id not problem at all, but when I used in foreach loop to search the id and get their names from another db It display only the 1st id name... For eg:If there are 5 id, but when I search the id to get the name from another db it shows the 1st id name only.What's the problem I don't know pls help me.
You could get it done (getting names list) by directly using join() method like this :
public function fetch_emp()
{
$this->db->select('emp_name');
$this->db->from('emp');
$this->db->join('employee_master', 'employee_master.emp_id = emp.emp_id');
$res=$this->db->get();
return $res->result();
}
How would I write an Zend DB query to select all from the column ID?
So far I have tried:
public function getLatestUserID()
{
$ids = $this->select()
->where('id = ?');
return $ids;
}
But to no avail.
You just want the id column,
You failed to call an execute command.
try:
//assuming you are using a DbTable model
public function getLatestUserID()
{
$ids = $this->fetchAll('id');
return $ids;
}
I would do it like this, because I use the select() object for everything:
public function getLatestUserID()
{
$select = $this->select();
//I'm not sure if $this will work in this contex but you can out the table name
$select->from(array($this), array('id'));
$ids = $this->fetchAll($select);
return $ids;
}
The first two examples should return just the id column of the table, now if you actually want to query for a specific id:
public function getLatestUserID($id)
{
$select = $this->select();
$select->where('id = ?', $id);
//fetchAll() would still work here if we wanted multiple rows returned
//but fetchRow() for one row and fetchRowset() for multiple rows are probably
//more specific for this purpose.
$ids = $this->fetchRow($select);
return $ids;
}
make sure your class containing getLatestUserID does extend Zend_Db_Table_Abstract also :
$ids = $this->select()->where('id = ?'); can't work because where('id = ?'); expects an id value like where('id = ?', $id);
if what you want is the latest inserted row's Id use :
$lastInsertId = $this->getAdapter()->lastInsertId();
(however if you are using an oracle database this will not work and you should use $lastInsertId = $this->getAdapter()->lastSequenceId('USER_TABLE_SEQUENCE'); )
I get a really anoying error when I try to edit an entry from a table, in tutorial they always use getTable()->find(), but I need to verify that the person logged in is the owner of that entry here what I did:
In the action:
public function executeEdit(sfWebRequest $request)
{
$id = $request->getParameter('id');
$userid = $this->getUser()->getGuardUser()->getId();
$ad = Doctrine_Core::getTable('BambinbazarArticles')->getMyAd($id, $userid);
$this->forward404Unless($ad, sprintf('Object bambinbazar_articles does not exist (%s).', $request->getParameter('id')));
$this->form = new BambinbazarArticlesForm($ad);
}
In the model:
public function getMyAd($id, $userid)
{
$q = $this->createQuery('c')
->where('c.id = ? ', $id)
->addWhere('c.userid = ? ', $userid);
return $q->execute();
}
I tried it with and without the ->execute(), did doctrine clean, cleared cache, rebuilded model,
Always get the same error 'The "%s" form only accepts a "%s" object.
If I use the Doctrine_Core::getTable('BambinbazarArticles')->find() it work, but of course, i need more than that..
I am becoming crazy over this.
execute() can return multiple rows; effectively you're getting a recordset back, rather than the individual object that your form is expecting. Try fetching a single object, using, e.g.:
return $q->execute()->getFirst();
or
return $q->fetchOne();
Its probably because your query is returning a Doctrine_Collection, not the actual Doctrine_Record youre expecting. Instead of execute use fetchOne.
public function getMyAd($id, $userid)
{
$q = $this->createQuery('c')
->where('c.id = ? ', $id)
->addWhere('c.userid = ? ', $userid)
->limit(1);
return $q->fetchOne();
}