Yii2 - insert relational data with junction table, many-many connection - yii2

I have a problem with Yii2 (Stable).
I have a Content(PK:id) table, I have a Tag(PK:id) table, and I have a junction table called Content_Tag (PK:content_id, tag_id). I'd like to use it for tagging, like WP tags.
All controllers and models are created with gii.
I have two problems:
If I create a new content, I'd like to save some new tags to the Tag table via the Content_Tag table. How can I do that? With link()?
What if there are tags (I know the ids) in the tag table, I'd like to connect only with the Content table via the junction table, without inserting into the Tag table. How can I do this?
I don't want to write native SQL command, I'd like to use the Yii2 built in functions like link() or via() or viaTable().
Thanks for your help!

I created a behavior to help handle do this, basically you do:
$content = Content::findOne(1);
$tags = [Tag::findOne(2), Tag::findOne(3)];
$content->linkAll('tags', $tags, [], true, true);
You can get the behavior here:
https://github.com/cornernote/yii2-linkall
If you'd prefer to do it without the behavior, something like this:
// get the content model
$content = Content::findOne(1);
// get the new tags
$newTags = [Tag::findOne(2), Tag::findOne(3)];
// get the IDs of the new tags
$newTagIds = ArrayHelper::map($newTags, 'id', 'id');
// get the old tags
$oldTags = $post->tags;
// get the IDs of the old tags
$oldTagIds = ArrayHelper::map($oldTags, 'id', 'id');
// remove old tags
foreach ($oldTags as $oldTag) {
if (!in_array($oldTag->id, $newTagIds)) {
$content->unlink('tags', $oldTag, true);
}
}
// add new tags
foreach ($newTags as $newTag) {
if (!in_array($newTag->id, $oldTagIds)) {
$content->link('tags', $newTag);
}
}

If you created models using gii then you might seen in the model the relationship is done like:
/**
* #return \yii\db\ActiveQuery
*/
public function getContent()
{
return $this->hasMany(Content_Tag::className(), ['content_id' => 'id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getContent()
{
return $this->hasMany(Tag::className(), ['tag_id' => 'tag_id'])->viaTable('content_tag', ['content_id' => 'id']);
}
If you want to save in Content_Tag table based on Content and Tag table then in controller you can use:
public function actionCreate()
{
$model = new Tag();
$content = new Content();
$content_tag = new Content_tag();
if($model->load(Yii::$app->request->post()) && $model->save()){
$model->save(false);
$content_tag->tag_id = $model->id;
$content_tag->content_id = $model->content_id;
$content_tag->save(false);
if($model->save(false))
{
Yii::$app->getSession()->setFlash('success', 'Created successfully');
return $this->render('create',[
'model' => $model,
'content' => $content,
'content_tag' => $content_tag
]);
}
}
else
{
return $this->render('create', [
'model' => $model,
]);
}
}
You can use link() to save. I am also searching for that as I didn't use that.

Related

Yii2: Filter query by pivot table when using `joinWith()`

Take the following sample Cart model. It has a CartItem "pivot record/table" which links it to Item.
class Cart extends ActiveRecord {
public function getCartItems() {
return $this
->hasMany(CartItem::class, ['cart_id' => 'id'])
->inverseOf('cart');
}
public function getItems($callback = null) {
return $this
->hasMany(Item::class, ['item_id' => 'id'])
->via('cartItems', $callback);
}
}
(Example #1) At this point I would be able to filter either by Item's activequery or CartItem's query like so:
$booksAddedToCartSinceYesterday = $cart
->getItems(function($cartItemQuery) {
$cartItemQuery->andWhere('cartItem.created_at > NOW()');
})
->andWhere(['item.category' => 'books']);
(Example #2) But how do I accomplish the same when I use the static find() method in combination with joinWith()? In the following example I am only able to filet by Item's ActiveQuery, but I no longer have any reference to the CartItem's ActiveQuery object:
$booksAddedToCartSinceYesterday = Cart::find()
->andWhere(['cart.user_id' => $some_user_id])
->joinWith([
'items' => function($itemQuery) {
$itemQuery->andWhere(['item.category' => 'books']);
},
]);
How do I modify the code above so that I am able to filter CartItem junction table records like I did in my example #1? How do I access the junction ActiveQuery object so that I can call $cartItemQuery->andWhere('cartItem.created_at > NOW()');?
you can pass any variable value in anonymous function with use keyword link below
make your magic code here for filter or any
->joinWith([
'items' => function($itemQuery) use ($var1,$var2){
$itemQuery->andWhere(['item.category' => 'books']);
$itemQuery->andWhere(['some_condition' => $var1]); <<<---------
},
]);

Many to many relationships in Yii2

I am trying to create a many to many relationship between a profile and several fields within that profile including languages and specialities. I have looked at several implementations and understand that there are several extensions, but I am required to minimise usage of extensions.
I have created the proper migration...this is a skeleton and the user table is purely for logins and OAuth...so keys can be ignored. As you can see in my controller I don't really know the way forward at this point. My language model is for all intensive purposes static from this controller(It is controlled by an admin backend). What is working? If I make a couple modifications to the below code then the checkboxlist will display with the proper checked items that I manually added to the lookup table. Trying to modify the lookup table from code, I have been unable to do unless I populate the $languageModel with a findOne(knownPK), however that is not usable, because multiple checkboxes can be selected resulting in an array and the link command requires ActiveRecordInterface which is singular. Ideally I would like to simply use
$languageModel->load(Yii::$app->request->post(),$trainerModel->formName());
but that isn't working.
Additionally, is there a mechanism within the framework to remove lookups or is that done manually. Any help or insight would be helpful. Thank you in advance.
public function safeUp()
{
$this->createTable('student', [
'id' => $this->primaryKey(),
'user_id' => $this->integer()->notNull(),
]);
$this->createTable('language', [
'id' => $this->primaryKey(),
'language' => $this->string(63),
]);
$this->createTable('student_language',[
'id' => $this->primaryKey(),
'language_id' => $this->integer(),
'student_id' => $this->integer()
]);
$this->addForeignKey('fk-student-language-language', 'student_language', 'language_id', 'language', 'id', 'CASCADE', 'CASCADE');
$this->addForeignKey('fk-student-language-student', 'student_language', 'student_id', 'student', 'id', 'CASCADE', 'CASCADE');
$this->addForeignKey('fk-student-user-user_id', 'student', 'user_id', 'user', 'id', 'CASCADE', 'CASCADE');
}
My student Active Record
/**
* #return \yii\db\ActiveQuery
*/
public function getstudentLanguages()
{
return $this->hasMany(studentLanguage::className(), ['student_id' => 'id']);
}
public function getLanguages(){
return $this->hasMany(Language::className(),['id'=>'language_id'])->viaTable('student_language',['student_id'=>'id']);
}
My Language Model
/**
* #return \yii\db\ActiveQuery
*/
public function getstudentLanguages()
{
return $this->hasMany(studentLanguage::className(), ['language_id' => 'id']);
}
public function getLanguages(){
return $this->hasMany(student::className(),['id'=>'student_id'])->viaTable('student_language',['language_id'=>'id']);
}
My Controller
public function actionProfile()
{
if (Yii::$app->user->isGuest) {
throw new UnauthorizedHttpException('This page requires you to be logged in');
} else {
$user_id = Yii::$app->user->identity->getId();
$studentModel = $this->findstudentModelByUserId($user_id);
if (is_null($studentModel)) {
$studentModel = new student();
$studentModel->setAttribute('user_id', $user_id);
$studentModel->save();
}
$languageModel = ??????????????????
$studentModel->load(Yii::$app->request->post()) && $studentModel->save() && $studentModel->link('languages',$languageModel);
}
return $this->render('profile', ['model' => $studentModel]);
}
My View
<?= $form->field($model, 'languages')->checkboxList(\common\models\Language::find()->select(
['language', 'id'])->indexBy('id')->column(), ['prompt' => 'select Language']); ?>
This is my solution at this point, however I am interested to hear improvements.
Note: There is no error checking etc...just functional code.
I added this to the student activerecord class
public function linkMultiple( $name,Array $models){
studentLanguage::deleteAll(['student_id' =>$this->id]);
foreach($models as $model){
$this->link($name, $model);
}
return true;
}
Modified my Controller action to the following
public function actionProfile()
{
if (Yii::$app->user->isGuest) {
throw new UnauthorizedHttpException('This page requires you to be logged in');
} else {
$user_id = Yii::$app->user->identity->getId();
$studentModel = $this->findstudentModelByUserId($user_id);
if (is_null($studentModel)) {
$studentModel = new student();
$studentModel->setAttribute('user_id', $user_id);
$studentModel->save();
}
$languages = Yii::$app->request->post('student')['languages'];
$languageModels = Language::findAll($languages);
$studentModel->load(Yii::$app->request->post()) && $studentModel->save() && $studentModel->linkMultiple('languages',$languageModels);
}
return $this->render('profile', ['model' => $studentModel]);
}

cakephp 3 + can't update database record when using translate behavior and 'contain'

I am using CakePHP 3 and trying to do some pretty basic stuff.
I have two tables, articles and tags.
Articles belongs to tags, and I made table tags translatable by attaching Translate behavior.
class ArticlesTable extends Table {
public function initialize(array $config) {
$this->addAssociations([
'belongsTo' => ['Tags']
]);
}
}
class TagsTable extends Table {
public function initialize(array $config) {
$this->addAssociations([
'hasMany' => ['Articles'],
]);
$this->addBehavior('Translate', ['fields' => ['name']]);
}
}
In Article controller I have edit function:
class ArticlesController extends AppController {
public function edit($id = null) {
$article = $this->Articles->get($id);
if ($this->request->is(['post', 'put'])) {
$this->Articles->patchEntity($article, $this->request->data);
if ($this->Articles->save($article)) {
$this->Flash->success(__('Your article has been updated.'));
return $this->redirect(['action' => 'edit',$id]);
}
$this->Flash->error(__('Unable to update your article.'));
}
$this->request->data = $article;
$tags = $this->Articles->Tags->find('list');
$this->set('tags', $tags);
}
}
In AppController I am setting locale language and at this point everything works fine, in edit.ctp file tags names are in local language and updating is working as it should.
BUT, when I replaced following line in edit function in ArticlesController:
$article = $this->Articles->get($id);
with line:
$article = $this->Articles->get($id, ['contain' => ['Tags']]);
I can no longer update article's tag.
If I change body and tag in my edit form, only new body is saved to my database. No error occurred, but tag_id is simply not changing.
If I remove translate behavior from the tags table, tags are not shown in local language, but can be updated again.
I am completely stuck, have no idea in which direction to search, why I can not use translate behavior and 'contain' at the same time?
Any help is greatly appreciated.

How to insert same data record to multiple table on Yii2

I'm using yii2-advanced. I've several table :
tb_user:(iduser(PK),username),
tb_profile:(id,iduser(FK)),
tb_status:(id,iduser(FK))
My question is how can i insert iduser(PK) from tb_user to iduser(FK) on tb_profile and tb_status after i push the signup button.
For a while i think i must to do some modification of bevahiours() function on User model and i found some error, or adding trigger syntax on the table ? (i think this is not a good ways).
Is there anyone who can help me, how to solve my problem ?
this is the User model before the modification :
<?php
namespace common\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
/**
* #inheritdoc
*/
public static function tableName()
{
return '{{%user}}';
}
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'timestamp' => [
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => 'created_at',
ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at',
],
'value' => function () {return date('Y-m-d h:m:s');},
],
];
}
/**
* #inheritdoc
*/
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
];
}
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
}
?>
The Controller :
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
I had similar situation in one of my project where i had 2 tables like user,user_image where user_id was foreign key to add the path.
For those kind of situation you can use either of following approach
1.Insert record in both table on click of signup button. You will have to write update action accordingly.
$user = new User();
$user->name = "John"
$user->email = "John#gmail.com"
//Add if any other fields in table
$user->save(); //save the record
$user_image = new UserImage();
$user_image->user_id = $user->id;
$user_image->image = "image path"
//Add any other images here
$user_image->save();//save the record
2.You can also call create action of UserImage and do the same. If you use this approach than you might also need to use any other unique column to find the id of that user and use it to insert new record,for example in my table email is unique column so i can write following code in UserImage and get the id
$user = User::findOne(['email' => 'john#gmail.com']);//this will return whole row
$user_image->user_id = $user->id;
$user_image->image = "image path"
//Add any other images here
$user_image->save();//save the record
And that way you can use the code as per it suits your need
Thank you

Yii2 Select only few columns from related model

In controller i have:
public function actionGetItems()
{
$model = new \app\models\WarehouseItems;
$items = $model->find()->with(['user'])->asArray()->all();
return $items;
}
In WarehouseItem model i have standard (created by gii) relation declaration:
public function getUser()
{
return $this->hasOne('\dektrium\user\models\User', ['user_id' => 'user_id']);
}
How can i control which column data do i get from "user" relation? I currently get all columns which is not good as that data is being sent to Angular in JSON format.
Right now i have to loop trough $items and filer out all columns i dont want to send.
You should simply modify the relation query like this :
$items = \app\models\WarehouseItems::find()->with([
'user' => function ($query) {
$query->select('id, col1, col2');
}
])->asArray()->all();
Read more : http://www.yiiframework.com/doc-2.0/yii-db-activequerytrait.html#with()-detail
Your code should go this way.
public function actionGetItems()
{
$items = \app\models\WarehouseItems::find()
->joinWith([
/*
*You need to use alias and then must select index key from parent table
*and foreign key from child table else your query will give an error as
*undefined index **relation_key**
*/
'user as u' => function($query){
$query->select(['u.user_id', 'u.col1', 'u.col2']);
}
])
->asArray()
->all();
return $items;
}
Inside WarehouseItem model
/**
* #return ActiveQuery
*/
public function getUser()
{
$query = User::find()
->select(['id', 'col1', 'col2'])
->where([
'id' => $this->user_id,
]);
/**
* Default hasOne, setup multiple for hasMany
* $query->multiple = true;
*/
return $query;
}