can't get relation's name via listdata - yii

I am not sure why I can't get the columns from my other tables via my relations. I was thinking is it because of my scope? After i had a default scope in my models, everything seems to be out of place, even if i use resetscope() at some places. Some sections I can't get to my relation columns; when that happens, I'd have to use Model::model->findbypk(n)->name.. that doesn't look pretty.
the id shows if i don't have the relations, but the name is blank when i put the relation name.
CHtml::listData(Model::model()->findAll(),'product_id','main.product_name'),
my model defaultscope is pretty basic:
return array(
'condition'=>'store_id1=:store_id OR store_id2=:store_id' ,
'params' => array(':store_id' => $store_id)
);

You can change the way you use your model like below:
Model::model()->with('main')->findAll();

Related

Displaying data from a normalised m-m relationship

I have have 2 tables, ServiceProvider , Entity. There is a m-m relationship between them so I created a link table spEntity which contains the foreign keys from both the other tables.
I have backpack working fine on the 3 tables separately, I use the relationship type on the spEntity CRUD to show the names from the other 2 tables and this all works fine.
However, what I would like to do is when the ServiceProvider record is being created
show a list of all the entities
allow the user to select one and then when the save button is pressed
create the spEntity record.
I have tried
protected function setupCreateOperation()
{
CRUD::setValidation(ServiceProviderRequest::class);
CRUD::field('ServiceProviderName');
CRUD::field('ServiceProviderEmailAddress');
CRUD::field('ServiceProviderDescription');
CRUD::addfield(['name'=>'Entity',
'type'=>'relationship',
'attribute' => 'EntityName',
'pivot'=>true,
'relation_type'=>'belongstomany'
]);
}
but I get the error :
BadMethodCallException PHP 8.1.7 9.19.0
Method Backpack\CRUD\app\Library\CrudPanel\CrudPanel::relationAllowsMultiple does not exist.
Table relations
Is this possible?
Try updating laravel-backpack/CRUD because seems to be an old bug.
Partial solution.
The problem was in my model definition. I need to add in the m-m relationship there.
Model
public function entities()
{
return $this->belongsToMany(Entity::class,'SPEntity','Entity_idEntity','ServiceProvider_idServiceProvider')
->withPivot('idSPEntity')
->withTimestamps();
}
then in the Crud controller
CRUD::addfield(['name'=>'entities',
'type'=>'select2_multiple',
'attribute' => 'EntityName',
'pivot'=>true,
'relation_type'=>'belongstomany'
]);
this now displays the field correctly and I can add further entities to the Service Provider.
However the information is not saved.

Yii recognise timestamp column

I'm using giix to extend model (and crud) behavior. In this I would like to handle columns of type timestamp (that already exist in my model) specifically, rather like autoincrement fields are handled. (Ignored and not shown, that is.) However, there is no property $column->isTimestamp. I would like to add this somewhere, but I'm rather at loss what the best place for this would be. Do I put it in giix somewhere, or do I have to extend the column-baseclass?
Edit: I want to ignore them from every view, for every table. Since this is a lot of work, and it's something I always want, I'd like to automate it. Adapting the generators seems to make most sense, but I'm not sure what the best way to do it would be.
Here is the process:
Extend your database schema, if you are on MySQL it is CMysqlSchema.
Extend CMysqlColumnSchema and add a "isTimestamp" attribute.
In your CMysqlSchema sub-class extend createColumn and test for a timestamp, you'll see that Yii makes simple string comparisons here to set it's own flags. Set "isTimestamp" in your CMysqlColumnSchema here.
Tell Yii to use your schema driver like this in your components section in the config:
'db' => array(
'connectionString' => 'mysql:host=localhost;dbname=database',
'username' => '',
'password' => '',
'driverMap' => array('mysql' => 'CustomMysqlSchema'),
),
You will need to query the column schema, I've not used giix but find where it is generating the views, it should be looping through either the model attributes or the underlying table schema.
If it is looping through the schema:
//you can also ask Yii for the table schema with Yii::app()->db->schema->getTable[$tableName];
if ('timestamp' === $tableSchema->columns[$columnName]->dbType)
continue; //skip this loop iteration
If it loops over the attributes:
$dbType = Yii::app()->db->schema->getTable[$model->tableName]->columns[$modelAttribute]->dbType;
if ('timestamp' === $dbType)
continue; //skip this loop iteration

Yii - one controller multiple urls

I'm trying to create two Yii models that are very similar and can share the same database table. One is a 'question' and one is an 'article'. They both share a title, body, and author. 'Question' has an additional field in the table that 'article' does not need to interact with called follow_up.
Most methods and validation is the same, but there are some tiny differences that could easily be done with if statements. The main problem I'm seeing is the URL, I want separate URLs like site.com/question and site.com/article but have them both interact with the same model, controller, and views.
How can this be done?
Use the urlManager component in the Yii config to set routes for /article and /question to go to the same controller, and then either use different actions or different parameters to differentiate between the two. Since you said they are almost identical, I would suggest different parameters and a single action as follows:
array(
...
'components' => array(
...
'urlManager' => array(
'question/<\d+:id>' => 'mycontroller/myaction/type/question/id/<id>',
'article/<\d+:id>' => 'mycontroller/myaction/type/article/id/<id>',
),
),
);
Of course you'll have to modify that for your needs, but that's the general setup. Look here for more information: http://www.yiiframework.com/doc/guide/1.1/en/topics.url

Can anyone explain how CDbCriteria->scopes works?

I've just checked the man page of CDbCriteria, but there is not enough info about it.
This property is available since v1.1.7 and I couldn't find any help for it.
Is it for dynamically changing Model->scopes "on-the-fly"?
Scopes are an easy way to create simple filters by default. With a scope you can sort your results by specific columns automatically, limit the results, apply conditions, etc. In the links provided by #ldg there's a big example of how cool they are:
$posts=Post::model()->published()->recently()->findAll();
Somebody is retrieving all the recently published posts in one single line. They are easier to maintain than inline conditions (for example Post::model()->findAll('status=1')) and are encapsulated inside each model, which means big transparency and ease of use.
Plus, you can create your own parameter based scopes like this:
public function last($amount)
{
$this->getDbCriteria()->mergeWith(array(
'order' => 't.create_time DESC',
'limit' => $amount,
));
return $this;
}
Adding something like this into a Model will let you choose the amount of objects you want to retrieve from the database (sorted by its create time).
By returning the object itself you allow method chaining.
Here's an example:
$last3posts=Post::model()->last(3)->findAll();
Gets the last 3 items. Of course you can expand the example to almost any property in the database. Cheers
Yes, scopes can be used to change the attributes of CDbCriteria with pre-built conditions and can also be passed parameters. Before 1.1.7 you could use them in a model() query and can be chained together. See:
http://www.yiiframework.com/doc/guide/1.1/en/database.ar#named-scopes
Since 1.1.7, you can also use scopes as a CDbCriteria property.
See: http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-named-scopes

One table two model

i have posts table
id
type enum(A,Q)
title
content
and i need controllers questions_controller and answer_controller to use
please lead the right way to
1-
make 2 models (question and answer) and use 'posts' as model's table
2-
use post model in questions_controller and answer_controller
For me, it should be one table has one model
So better use
$uses = array('Post'); in your controllers.
Update:
As far I understood you want to filter the data depending from the type column. Actually your db model is wrong, because except if they are totally unrelated your answers need to belong to the question. This mean you need an extra column parent_id which will determine what is the parent node (question) and child nodes (answers).
If we have this assumption, then you can set a relation in the model like:
class Post extends AppModel {
...
var $belongsTo = array(
'Parent' => array('className' => 'Post','foreignKey' => 'parent_id', 'conditions' => 'Parent.parent_id IS NOT NULL')
);
...
}
So you automatically have Post and Post->Parent. But I think that it would be better to have 2 tables - one which holds the questions and another the answers.