Check availability of foreign key value in the foreign table - yii

Say I have 2 tables, A and B.
B has a foreign key from A.
Whenever I insert data to table B, I should check availability of foreign key in the table A.
Is there any way to do this process instead of doing it manually ?
I have googled it by myself, and found that CExistValidator is probably what I want.
But I didn't find any comprehensive example for use of that validator.
If CExistValidator is the answer, can you give me some example ?
Thanks.

Let's say you have a class Category which has many Pages. You want to ensure that Page belongs to some existing Category:
class Page {
//...
public function rules()
{
return array(
array('category_id', 'exist', 'className' => 'Category', 'attributeName' => 'id'),
);
}
}

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.

Updating an object with Realm without a Primary Key

In my React-Native app, I need to update some objects but I can't do like the tutorial :
realm.write(() => {
// Create a book object
realm.create('Book', {id: 1, title: 'Recipes', price: 35});
// Update book with new price keyed off the id
realm.create('Book', {id: 1, price: 55}, true);
});
Because my objects don't have a primary key (and i don't want them to have primary key)
There is my try :
this.state.realm.write(() => {
this.state.realm.create('Bills', {type: this.state.billType,
creditor: this.state.billCreditor, month: this.state.billMonth,
year: this.state.billYear, price: this.state.billPrice}, true);
});
But this try obviously create an another object ^^
Is someone have an idea for my problem please? Thanks for all =)
Finally, I used UUID as Primary key ^^"
https://www.npmjs.com/package/react-native-uuid
Currently Realm doesn't support updating objects without primary keys. See this GitHub issue.
If you really want to achieve this, you will have to delete the object from Realm and then adding it with the updated values.
However, I wouldn't recommend this method. Creating a primary key in most cases is the optimal solution, so you should reconsider using it. The built in update method will in most cases have a better performance than any method you could write without using primary keys.

How to setup yii model relations right, is using 't' to refer to default table a good idea

Usage of 't' in model relations can give the error
"Column not found: 1054 Unknown column 't.etc' in 'on clause'."
It's the usage of 't' to refer to the current table in CActiveRecord Model relations.
I often stumble accross it when using ,findAll, CActiveDataProvider, etc
Sometimes it works sometimes it doesn't depending on what model you execute and from where.
I tried using tableAlias but it doesn't work. There must be an easy way.
How can I setup my models and it's relations in such a way that the relations are stable
and always works?
Here is an example of two classes to show the problem...
class Order extends CActiveRecord
{
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'author'=>array(self::BELONGS_TO, 'User', 'user_id'),
'shopproduct'=>array(self::BELONGS_TO, 'ShopProduct', 'product_id',
'with'=>array(
'tagsrelations',
),
),
);
}
}
class ShopProduct extends CActiveRecord
{
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'author'=>array(self::BELONGS_TO, 'User', 'user_id'),
'tagsrelations'=>array(self::HAS_MANY, 'TagsRelations','',
'on'=>' tagsrelations.tbl_uuid = t.uuid ',
'with'=>'tag',
'order'=>'tag.name ASC',
),
);
}
}
// works
$model=Order::model()->with('shopproduct')->findAll();
// doesn't work
// "Column not found: 1054 Unknown column 't.uuid' in 'on clause'. The SQL statement executed was"
$model=ShopProduct::model()->with('tagsrelations')->findAll();
Maybe someone can explain why this isn't working in an understanding way.
How to fix this one once and for all. BELONG TO relations usually work.
What is the best to make an HAS MANY relationship that always works
Do you need the t only for the join or for some specific purpose? Because for the join this is not the right way to do it. It should be done sth like this:
'tagsrelations'=>array(self::HAS_MANY, 'TagsRelations', array('tbl_uuid'=>'uuid')),
Of course you can then add the with condition if you need that as well. But the join should be done this way.

Yii CActiveRecord: find related data, but not using the primary key

I have this code in my model for "Application", I'm trying to get all the related "Campaign" objects
public function relations()
{
return array(
'campaigns' => array(self::HAS_MANY, 'Campaign', 'appKey'),
);
}
My problem is, the 'appKey' field in the campaigns table is not the primary key of the applications table and this is what Yii is using to try and find the campaigns.
The primary key of my applications table is 'id' but I would like it to use 'appKey'. How can I update my relations method to do this without making it the primary key?
Thanks.
You could set up a named scope in the Campaign model, like so:
public function byApplication($appKey)
{
$this->getDbCriteria()->mergeWith(array(
'condition'=>'appKey = :appkey',
'params'=>array('appKey'=>$appKey),
));
return $this;
}
And call it like this:
$campaigns = Campaign::model()->byApplication($appKey);
Or, as Irobb said, just set up a query function in your Application model instead of using an actual Relation, like so:
public function getCampaigns() {
return Campaign::model()->findallbyAttributes(array('appKey'=>$this->appKey));
}
And call it like a regular relation on your Application $model:
$campaigns = $model->campaigns; // remember with Yii you can call getters w/o the 'get'
A couple of things... AR is primarily useful for modeling a single table to a class, with a well-defined primary key... Anything else I would use the query builder.
Note: AR is not meant to solve all database-related tasks. It is best
used for modeling database tables in PHP constructs and performing
queries that do not involve complex SQLs. Yii DAO should be used for
those complex scenarios.
http://www.yiiframework.com/doc/guide/1.1/en/database.ar
AR relies on well defined primary keys of tables. If a table does not
have a primary key, it is required that the corresponding AR class
specify which column(s) should be the primary key by overriding the
primaryKey() method as follows,
public function primaryKey() {
return 'id';
// For composite primary key, return an array like the following
// return array('pk1', 'pk2'); }

Referencing table with two different foreign keys to the same table in Kohana ORM

table user:
|id|name|employee_priority_id|user_priority_id|
table priority:
|id|name|
As you can see, there are two foreign fields to the same table. But Kohana ORM default looks for a field called priority_id, which doesn't exist.
Is there a way to let Kohana ORM know that those two fields are an foreign key to that table.
You can use 'aliasing' as documented # http://docs.kohanaphp.com/libraries/orm/advanced#aliasingenhancing_the_meaning_of_your_relationships
So in your case, your User_Model would be:
class User_Model extends ORM {
protected $belongs_to = array('employee_priority' => 'priority', 'user_priority' => 'priority');
}
BTW, according to Kohana's convention table names ought to be in plural form unless you override the $table_name, e.g:
class Priority_Model extends ORM {
protected $table_name = 'priority';
}