Eager loading same model multiple times in a model - database

I have a Model named Player with 'id' and 'shortname'.
I have another Model named Team with 'id', 'teamname', 'player_1_id', 'player_2_id' and 'player_3_id'.
I am trying to use relations:
// in Model Team
public function players()
{
return $this->hasOne('App\Player', 'id','player_1_id')
->hasOne('App\Player', 'id','player_2_id')
->hasOne('App\Player', 'id','player_3_id');
}
// In controller
$resource = Team::with('players')->get(); doesnt work.
In this case, Which is the best(fastest) way to use eagerloading?
Thanks in advance...

You should read about database normalization. It does not make sense to store player_1_id, player_2_id and player_3_id in teams database. What if team will contain 20 players? You will create another fields?
You should either add team_id into Player model (in case players always belongs to only one team) or create extra table where you will store connections between players and teams.

Related

Laravel relationship : relationship that does not return me what I ask

rI am new to laravel 7 and I still have a few small difficulties.
I have two tables: users and services. These two tables have a relation to retrieve a user's service.
$users= User::with('poseur')->get();
It returns all users even those who do not meet the conditions of my relationship.
I use scope in service model:
public function scopePoseurs(){
return $query->whereRaw('slug','pos')
}
And i use belongsTo relation in user model :
public function poseur(){
return $this->belongsTo('App\Service')->poseurs();
}
Exemple: we hase 2 users:
first: Daniel have service slug = 'pos',
second: Patrick have service slug ='dev'
When i use $users=User::with('poseur')->get();, i see Daniel and Patrick.
While there should be only Daniel.
Can you help me understand ?
Thanks !
with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models.
If you want to return all user, that has relation with poseur only, then use has() method :
$users= User::has('poseur')->get();
Ther is also a method called whereHas(), which allows you to specify additional filters for the related model to check :
$users = User::whereHas('poseur', function($q){
$q->where('created_at', '>=', '2020-01-01 00:00:00');
})->get();

Yii2 + Redis as Database

I want to use Yii2 and redis as database.
So far, I got Redis ActiveRecord Class for Yii2 from Here.
link1
link2
but, I got a problem. WHY THIS CLASS ADDS ANYTHING AS HASH IN REDIS????
Above that I cant Find in which pattern it Insert data. I add one user and it will add a user under user:xxx namespace and another record under s:user:xxx and so on but none of theme has any fields that i defined in attributes!! only contain IDs.
I know that a Key-value type database and RDBMS are different and also know how can implement relation like records in Redis, but I don't know why it will only save IDs.
I could not find any example of using redis ActiveRecords so far.
There is one in here and its not good enough.
So here is my main wuestion: how can add data to redis Using activeRecords and different data types In YII2?
And if its impossible with ActiveRecords what is the best solution? in this case
ANOTHER QUESTION: is it possible to use a Model instead and write my own model::save() method? and what is the best data validation solution at this rate?
Actually I want to make a telegram bot, so i should get messages and send them in RabitMQ and get data in a worker, do the process and save results to Redis, and finally send response to user through the RabitMQ.
So I need to do a lot of validations AND OF COURSE AUTHENTICATIONS and save and select and range and save to sets an lists and this and that ....
I want a good way to make Model or active record or the proper solution to validation, save and retrieve data to Redis and Yii2.
Redis DB can be declared as a cache component or as a database connection or both.
When it is declared as a cache component (using the yii/redis/cache) it is accessible within that component to store key/value pairs as shown here.
$cache = Yii::$app->cache;
// try retrieving $data from cache
$data = $cache->get($key);
// store $data in cache so that it can be retrieved next time
$cache->set($key, $data);
// one more example:
$access_token = Yii::$app->security->generateRandomString();
$cache->add(
// key
$access_token,
// data (can also be an array)
[
'id' => Yii::$app->user->identity->id
'name' => Yii::$app->user->identity->name
],
// expires
60*60*3
);
Also other components may start using it for caching proposes like session if configured to do so or like the yii\web\UrlManager which by default will try to cache the generated URL rules in whatever valid caching mechanism defined under the config file's cache component as explained here. So it is normal to find some stored data other than yours in that case.
When Redis is declared as a DB connection like in the links you provided which means using the yii\redis\Connection class you can make your model extending its \yii\redis\ActiveRecord class as any other ActiveRecord model in Yii. The only difference I know so far is that you need to define your attributes manually as there is no DB schema to parse for NoSQL databases. Then just define your rules, scenarios, relations, events, ... as any other ActiveRecord model:
class Customer extends \yii\redis\ActiveRecord
{
public function attributes()
{
return ['id', 'name', 'address', 'registration_date'];
}
public function rules()
{
return [
['name', 'required'],
['name', 'string', 'min' => 3, 'max' => 12, 'on' => 'register'],
...
];
}
public function attributeLabels() {...}
...
}
All available methods including save(), validate(), getErrors(), ... could be found here and should be used like any other ActiveRecord class as shown in the official guide.

How to create objects that have relationships when using Backand BaaS?

I am using Backand BaaS for my ionic app. My model consists of two tables:
1. Users
2. Trips
A one-to-many relationship has been established between 'Users' and 'Trips'.
'Users' has a collection field that is a collection of 'Trips' and 'Trips' has a owner field that is an object of 'Users'.
What is the correct way to create an object so that upon creating I am assigning the correct owner ('Users' object) to 'Trips' collection field ?
When POSTing a new Trip use this for the Trip Object
{
tripName:"asdf"
owner:1
}
In the users object it will look like this
{
id:1
fName:"david"
trips:[{__metadata: {id: 1}, tripName: "asdf"}]
}

Sequelize 2 Many to Many relationship

I have videos that can be liked by users and commented by users so I need 2 many to many associations.
User model
User.belongsToMany(models.Video,{ through: 'user_like_video' });
User.belongsToMany(models.Video, { through: 'user_comment_video' });
Video model
Video.belongsToMany(models.User, {through: 'user_like_video'});
Video.belongsToMany(models.User, {through: 'user_comment_video'});
My resulting schema in DB is :
The many to many relationship between video a tags work well I can use the method getTags() to retrieve all the tags from a video but how are created methods when you have 2 (many to many relationship) ?
When I use user.getVideos(), I only get the last relation registered which is here user_comment_video.
I finally find a way :
Video.belongsToMany(models.User, {through: 'user_like_video', as: 'Like'});
Video.belongsToMany(models.User, {through: 'user_comment_video',as: 'Comment'});
this exposes methods getLike() and getComment()

AppEngine Datastore get entities that have ALL items in list property

I want to implement some kind of tagging functionality to my app. I want to do something like...
class Item(db.Model):
name = db.StringProperty()
tags = db.ListProperty(str)
Suppose I get a search that have 2 or more tags. Eg. "restaurant" and "mexican".
Now, I want to get Items that have ALL, in this case 2, given tags.
How do I do that? Or is there a better way to implement what I want?
I believe you want tags to be stored as 'db.ListProperty(db.Category)' and then query them with something like:
return db.Query(Item)\
.filter('tags = ', expected_tag1)\
.filter('tags = ', expected_tag2)\
.order('name')\
.fetch(256)
(Unfortunately I can't find any good documentation for the db.Category type. So I cannot definitively say this is the right way to go.) Also note, that in order to create a db.Category you need to use:
new_item.tags.append(db.Category(unicode(new_tag_text)))
use db.ListProperty(db.Key) instead,which stores a list of entity's keys.
models:
class Profile(db.Model):
data_list=db.ListProperty(db.Key)
class Data(db.Model):
name=db.StringProperty()
views:
prof=Profile()
data=Data.gql("")#The Data entities you want to fetch
for data in data:
prof.data_list.append(data)
/// Here data_list stores the keys of Data entity
Data.get(prof.data_list) will get all the Data entities whose key are in the data_list attribute

Resources