Documentation Level: 
Intermediate
Documentation Status: 
No known problems

Database api functions can be chained together, for example:

<?php
$result = db_select('mytable')
->fields('mytable')
->condition('myfield', 'myvalue')
->execute();
?>

However not all functions can be chained in this manner without causing your code to break.

Functions that cannot be chained together have to be done like this:

<?php
$query = db_select('mytable');
$query->addField('mytable', 'myfield', 'myalias');
$query->addField('mytable', 'anotherfield', 'anotheralias');
$result = $query->condition('myfield', 'myvalue')
->execute();
?>

For a function to be chain-able its return value must be the query object itself for a function acting on the query object. You may also append a result set function after execute() such as fetchField() as in this example:

<?php
$number_of_records = db_select('mytable')
->condition('myfield', 'myvalue')
->countQuery()
->execute()
->fetchField();
?>

To find out the return value of any of the database API functions check out the Backdrop API documentation.

This page is here as a quick guide to which functions can and can not be chained.
The lists are not yet exhaustive lists but cover a lot of the commonly used functions.
Please feel free to add to these lists.

Note: If a function is not chain-able it means you cannot chain more functions after it. You can still chain functions before it.

Functions that can be chained:

  • addMetaData()
  • addTag()
  • comment()
  • condition()
  • countQuery()
  • distinct()
  • exists()
  • fields()
  • forUpdate()
  • groupBy()
  • having()
  • havingCondition()
  • isNotNull()
  • isNull()
  • notExists()
  • orderBy()
  • orderRandom()
  • range()
  • union()
  • where()
  • execute()

Functions that cannot be chained:

  • addExpression()
  • addField()
  • addJoin()
  • extend()
  • innerJoin()
  • join()
  • leftJoin()
  • rightJoin()