How to select particular field of db table from model? - zend-framework

Suppose that i have a table 't' with fields 'id' int 11, 'name' varchar 50, and 'description' text. if the text is very large, and i am querying the database with 'description' and without 'description', will there be any difference?
and how to select only 'id' and 'name' in the Model that extends Zend_Db_Table_Abstract class?

In term of perfomances I can't really help, but it should not make a big difference.
For your question about how to select fields in a query look at the following
class Model_DbTable_T extends Zend_Db_Table_Abstract{
protected $_name = 't'; // this line is optionnal if your table has the same name as the class
public function fetchSomeFields(){
$query = $this->select()
->from($this,
array('id')); // you could also include the 'as' statement in the field name to make it look like 'id as otherName'
return $this->fetchAll($query);
}
}

Related

Eloquent use default value if column is null

I want to use the default value if the column is null. For example:
Settings (Table):
id | website_id | column1 | column2
1 | 1 | null | null
Website.php:
<?php
namespace App\Models;
class Website extends Model
{
public function Setting(): HasOne
{
return $this->hasOne(IvendiFinanceCalculatorSetting::class)->withDefault([
'column1' => 'Default',
'column2' => 0,
The above is a hypothetical example, but you can see what I'm attempting to achieve. If I add a row to my table with a matching website id, but leave the other columns as null I want to return the defaults.
Currently if query the Website model with the settings relationship I get back the row but column1 and column2 is null rather than Default and 0.
dd(Website::query()->with('Setting')->find(1));
withDefault works when the relationship is null, not the field values. See Null Object Pattern for more information.
You might be better served by model events, specifically creating for when new IvendiFinanceCalculatorSetting records are inserted.
Then in the model's boot method or an observer class, you can set default setting values:
// IvendiFinanceCalculatorSettingObserver.php example
public function creating (IvendiFinanceCalculatorSetting $setting) {
$setting->setAttribute('column1', 'Default');
$setting->setAttribute('column2', 0);
}
Another approach is setting the default values directly in the model's attribute property:
/**
* The model's default values for attributes.
*
* #var array
*/
protected $attributes = [
'column1' => 'Default',
'column2' => 0
];

Add a Field to a CrudController that ONLY passes values to Store / Update Methods

I'm trying to handle how a field within a CrudController stores or updates the data on the particular model in a completely custom way. I would like the traitStore() and traitUpdate() methods to ignore this field entirely, but would like the data to still be passed in via the request. This is specifically in reference to a many-many relationship using a select2_multiple field.
I would like it so that the relationship ID's are passed via the request object to the Store or Update methods, but I DO NOT want the traitStore() or traitUpdate() methods to actually perform updates on that particular field reference.
For example...
I have this field within my crud controller
$this->crud->addField(
[
'label' => "Groups",
'type' => 'select2_multiple',
'name' => 'groups',
'entity' => 'groups',
'attribute' => 'title',
'model' => "App\Models\Group",
'pivot' => true
]
);
And I'm overriding the Store and Update Methods like so.
public function store()
{
$this->crud->setValidation(UserRequest::class);
// WOULD LIKE TO SAVE EVERYTHING BUT IGNORE THE GROUPS FIELD
$response = $this->traitStore();
// DO WHATEVER I WANT WITH GROUPS AT THIS POINT
$groups = $request->groups
return $response;
}
public function update()
{
$this->crud->setValidation(UserRequest::class);
// WOULD LIKE TO SAVE EVERYTHING BUT IGNORE THE GROUPS FIELD
$response = $this->traitUpdate();
// DO WHATEVER I WANT WITH GROUPS AT THIS POINT
$groups = $request->groups
return $response;
}
Looking at my comments I would like to get a reference to the groups and handle updating the model however I want.
I've tried to unset the groups value in the request, unset($this->request{'groups'}), but it still updates / removes the relationships when I do that.
Here is what you need to do to remove the references from being updated by the CrudController.
public function update()
{
$this->crud->setValidation(UserRequest::class);
$request = clone $this->request;
$this->crud->request->request->remove('groups');
$this->crud->removeField('groups');
$groups = $request->groups
$response = $this->traitUpdate();
return $response;
}
I found an easy way to ignore/pass form field.
Example:
In your form fields have first_name, last_name, gender and in your database is only have fullname, gender then you wanna create/update the form, it will show Column not found: 'first_name' not found...,
How to fix it:
Add $fillable in the model and fill the array data with name field that you want to store/update. In example case $fillable = ['fullname', 'gender'];
Then, just use mutators inside the model too.
public function setFullnameAttribute(){
return $this->attributes['fullname'] = \Request::input('first_name') . ' ' . \Request::input('last_name');
}
NB: You should have hidden field name 'fullname' in your CrudController.
$this->crud->addField(['name' => 'fullname', 'type' => 'hidden']);

Compound fields in search

I'm trying to get first name and last name from a related table
I've tried using an accessor on the related table which works fine when loading the page and for adding/editing but when searching it shows an error
Column not found: 1054 Unknown column 'FullName' in 'where clause'
This column obviously does not exist.
So I have this in my related model
{
return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
}
And under the Backpack crud Controller I have
$this->crud->addColumn([ // n-n relationship (with pivot table)
'label' => 'Account', // Table column heading
'type' => 'select',
'name' => 'user_id', // the method that defines the relationship in your Model
'entity' => 'user', // the method that defines the relationship in your Model
'attribute' => 'FullName', // foreign key attribute that is shown to user
'model' => "App\Models\BackpackUser", // foreign key model
]);
Where am I making a mistake, input would be very much appreciated.
That needs a real column.
You can use a view (like you already do) or a model_function column to format the table cell value in your model class - https://backpackforlaravel.com/docs/3.5/crud-columns#model_function
Just see what's simpler for you.
Note: if ordering or searching doesn't work as expected see https://backpackforlaravel.com/docs/3.5/crud-columns#custom-search-logic-for-columns and https://backpackforlaravel.com/docs/3.5/crud-columns#custom-order-logic-for-columns

Yii2: How to do a simple join query?

I am learning how to do simple queries using the Yii2 framework. I use PostgreSQL.
I am trying to join two tables and get the data from both tables with a where condition.
The tables are called Admins and Persons.
The join use field called idadm.
The condition is idadm = 33. This works great but the result has data only from the Admins table and I need data from the other table.
Here is my example:
$query = \app\models\Admins::find()
->select('*')
->leftJoin('persons', 'persons.idadm = admins.idadm')
->where(['admins.idadm' => 33])
->with('persons')
->all();
I am following the Yii2 official guide: http://www.yiiframework.com/doc-2.0/guide-db-active-record.html
Update: Here I show the updated code that doesn't solve de problem:
You need to write all column name in select().
$query = \app\models\Admins::find()
->select('admin.*,persons.*') // make sure same column name not there in both table
->leftJoin('persons', 'persons.idadm = admins.idadm')
->where(['admins.idadm' => 33])
->with('persons')
->all();
And also you need to define person table attributes in Admin model.
Second way is get records as array,so you dont need to define attributes in Admin model.
$query = \app\models\Admins::find()
->select('admin.*,persons.*') // make sure same column name not there in both table
->leftJoin('persons', 'persons.idadm = admins.idadm')
->where(['admins.idadm' => 33])
->with('persons')
->asArray()
->all();
Ensure that active record has required relations, e.g. something like follows:
class Admins extends \yii\db\ActiveRecord {
public function table() {
return "admins";
}
public function getPersons()
{
return $this->hasMany(Person::className(), ['idadm' => 'idadm']);
}
}
class Person extends \yii\db\ActiveRecord {
public function table() {
return "persons";
}
}
Then use joinWith to build query:
$query = Admins::find()
->joinWith('persons')
->limit(1);
$result = $query->createCommand()->getSql();
echo $result;
Here is produced query:
SELECT `admins`.* FROM `admins`
LEFT JOIN `person` ON `admins`.`idadm` = `person`.`idadm` LIMIT 1

Possible to use _referenceMap with join() on Zend_Db_Select?

Example:
class Products extends Zend_Db_Table_Abstract
{
protected $_name = 'products';
protected $_referenceMap = array(
'Bug' => array(
'columns' => array('bug_id'),
'refTableClass' => 'Bugs',
'refColumns' => array('bug_id')
)
);
}
$object = new Products();
$select = $object->select()->from()->Join('Bug');
Instead of defining the full join statement
As far as I can tell $_referenceMap is not used in that way. $_referenceMap defines the relationship that a table row has with other tables.
That's why the associated findDependentRowset(), findManyToManyRowset() and findParentRow() are found in Zend_db_Table_Row_Abstract. These methods create the Joins.
So to get the dependent rows from Bugs, using a select object, you would do something like this, assuming that Products has a one-to-many relationship with Bugs;
class Products extends Zend_Db_Table_Abstract
{
protected $_name = 'products';
protected $_dependentTables = array('Bugs');
}
class Bugs extends Zend_Db_Table_Abstract
{
protected $_referenceMap = array(
'Products' => array(
'columns' => array('bug_id')
,'refTableClass' => 'Products'
,'refColumns' => array('bug_id')
)
);
}
To get dependent rows you first have to fetch a parent row.
$products = new Products();
$productRow = $products->find(123)
->current();
You can refine the join by using Zend_Db_Select
$select = $products->select()
->where('foo_bar = ?', 'cheese')
->limit(2);
Finally querying the dependent rows by passing in the select object instead instead of a rule key.
$bugRowset = $productRow->findDependentRowset('Bugs', 'Products', $select);
I think this will work, I'll have to check tomorrow morning.
This is usefull for one row, but not for the whole table (or several rows). I usually need queries affecting more than one row... Zend should implement the option mentioned by Phliplip, or something similar:
$select = $object->select()->from()->Join('Bug');
Note: I mean, using only one query