foreignKey in model based on condition in cakephp - mysql

I am struck with one issue related to foreignKey concept.
I have two table users & user_relations.
users user_relations
id username id user_id friend_id status
1 abc 1 1 2 Accepted
2 def 2 2 3 Accepted
3 ghi 3 1 3 Accepted
here the friend_id is the foreign_key and my user_relations model looks like
public $belongsTo = array(
'Friend' => array(
'className' => 'User',
'foreignKey' => 'friend_id'
)
);
My conditions will be like
'conditions' => array(
"OR" => array(
'UserRelation.user_id' => $iLoggedUserId,
'UserRelation.friend_id' => $iLoggedUserId,
),
'ViewerRelationship.status' => 'Accepted'
)
Now when user "1" is logged in then he will get the info of users "2" & "3" based on foreignKey friend_id.
If user "2" gets logged in then, he is getting the info of users "2" & "3". But here I need to get the info of users "1" & "3". i.e., in one case it need to take the info based on the user_id not the friend_id
If I can keep the foreignKey in a condition I can get the result based on user_id or friend_id.
Any help please..!

I dont know how it is effective for you.
But it will solve your problem.
$respone = $this->UserRelation->find('all',
array('conditions'=> array(
'OR'=>array(
'UserRelation.user_id' => $iLoggedUserId,
'UserRelation.friend_id' => $iLoggedUserId
)
),
'fields' => array('UserRelation.*')
));
$reqFriendsId = array();
foreach($respone as $key => $val){
if($val['UserRelation']['friend_id'] == $iLoggedUserId){
array_push($reqFriendsId, $val['UserRelation']['user_id']);
}else{
array_push($reqFriendsId, $val['UserRelation']['friend_id']);
}
}
//For logged in user 1
Array
(
[0] => 2
[1] => 3
)
//For logged in user 2
Array
(
[0] => 1
[1] => 3
)

Related

How to have relationship in Laravel 5.7 based on a json data key saved in a table column?

I am using this Staudenmein package in Laravel and referring to this answer given by the package owner himself.
I have two tables, pets and notifications with models Pet and Notification.
The notifications table has a column called data which is of JSON dataType and stores JSON data
{"pet_id":"4","pet_type_id":1,"lost_report_id":3,"pet_sighting_id":21,"latitude":"22.676846","longitude":"88.338509"}
The key pet_id denotes the id column of the pets table. I need a relationship so that I can fetch the name of the pet from pets table.
By referring to the answer link given above, I wrote my Notification model like this:-
namespace App\Models;
use DB, App, Auth, Hash, Lang, Mail, Config, Exception, Validator, Globals;
use Illuminate\Database\Eloquent\Model;
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
use App\User;
use App\Models\AdminConfig;
use App\Models\ReceivedAppNotification;
class Notification extends Model
{
protected $casts = [
'data' => 'json'
];
public function notificationPet()
{
return $this->belongsTo('App\Models\Pet', 'data->pet_id');
}
}
When I am running the query like this:-
$notificationQuery = Notification::with('notificationPet')
->whereRaw("FIND_IN_SET('$userId', in_app_notification_receiver)")
->where(array(
'status' => Globals::SMALL_CHAR_ACTIVE,
'is_delete' => Globals::SMALL_CHAR_NO,
))->get()->toArray();
I get the notificationPet relationship as empty, ie. the data-set is like this:-
Array
(
[id] => 10
[title] =>
[message] =>
[data] => Array
(
[pet_id] => 4
[latitude] => 22.676846
[longitude] => 88.338509
[pet_type_id] => 1
[lost_report_id] => 3
[pet_sighting_id] => 34
)
[no_of_in_app_notification_receiver] => 2
[no_of_push_notification_receiver] => 1
[from_user] => 22
[in_app_notification_receiver] => 2,23
[push_notification_receiver] => 2
[status] => a
[is_delete] => n
[push_notification_sent] => n
[created_date] => 2020-03-19 13:23:17
[modified_date] => 2020-03-19 13:23:17
[created_at] => 2020-03-19 13:23:17
[updated_at] => 2020-03-19 13:23:17
[notification_pet] =>
)
However, I have a record in pets table with id = 4, already. So the relationship should not be empty.
What am I doing wrong?
Change:
protected $casts = [
'data' => 'json'
];
To:
protected $casts = [
'data' => 'array'
];

is it possible to get sub array from mysql query?

I have a query that prints record in an array, but I need one more array in the last field e.g
[0] = Array
[id] => 1
[name]=> test
[age]=> 25
[subjects]=> 3
[order_details] = array(
[0] => array(
'id' => 1
'company_id'=> 8
'purchase_invoice_id '=> 102
'model_id' => 1
'date' => 2015-12-1
'IMEI'=>7654367876
'color' => black
'purchase_price' => 500
'is_sold' => 1
'is_returned'=>1
)
can any one guide me ? I need order_details in sub array, but please make sure it shouldn't be from php I need one mysql query to sort it out.
Thanks

Why can I not update the foreign key of an object in a 1:1 association?

I have two models, User and Profile.
A User has_one Profile and a Profile belongs_to User.
Correspondingly, the Profile model has a user_id attribute.
The association works:
p = Profile.first
=> #<Profile id: 1, name: "Jack", ... , user_id: 1>
u = User.first
=> #<User id: 1, email: "jack#example.com", ... >
u.profile.id
=> 1
p.user.id
=> 1
p.user == u
=> true
u.profile == p
=> true
I can set the user_id field on a Profile directly:
p.user_id = 2
=> 2
p.save!
=> true
p.user_id
=> 2
But why can I not set the user_id like this:
u.profile.user_id = 2
=> 2
u.profile.save!
=> 2
u.profile.user_id
=> 1
You must refresh u.profile object. Try this:
u.profile.user_id = 2
=> 2
u.profile.save!
=> 2
u.profile.reload.user_id
=> 2
This is because original profile object is still loaded on memory in u.
Hope this help :)

CakePhp Containable too many queries

I'm using CakePHP 2.5.2 and having a bit of trouble searching for data efficiently.
In my application I've 3 tables, teams, players, skills... In teams there are 80 records, players 2400 records, skills 2400 records... I want to calculate the average skill of a team...
//Team model
public $actsAs = array('Containable');
public $hasMany = array('Player');
//Player model
public $actsAs = array('Containable');
public $hasOne = array('Skill');
public $belongsTo = array('Team');
//Skill model
public $actsAs = array('Containable');
public $belongsTo = array('Player');
My research is:
$team = $this->Team->find('all', array(
'contain' => array(
'Player' => array(
'Skill'
)
),
));
$this->set('team', $team);
that gives the expected result:
Array
(
[0] => Array
(
[Team] => Array
(
[id] => 1
[name] => my_team_name
)
[Player] => Array
(
[0] => Array
(
[id] => 000000419
[name] => Name
[surname] => Surname
[age] => 21
[team_id] => 1
[Team_id] => 1
[Skill] => Array
(
[id] => 20
[player_id] => 000000419
[skill] => 599
)
), ecc.....
This structure use at least 1680 queries... that are too much for me...
I've tried an other way, that involve just one query, returns a bad data structure but all the information that i need (also redundant). unfortunately follow this way i can not iterate in View to display what i need.
$player = $this->Team->Player->find('all', array(
'contains' => array(
'Skill',
),
that returns
Array
(
[0] => Array
(
[Player] => Array
(
[id] => 000000400
[nome] => my_player_name
[cognome] => my_player_surname
[nation_id] => 380
[age] => 29
[team_id] => 2
)
[Team] => Array
(
[id] => 2
[nome] => my_team_name
)
[Skill] => Array
(
[id] => 1
[player_id] => 000000400
[average] => 632
)
)
ecc.
Is there a way to iterate in VIEV to get the average skill of every team? Any other solutions?
Thanks!
You can use my plugin to solve this issue if you can upgrade CakePHP to 2.6 or later. The plugin has a high compatibility with ContainableBehavior, but generates better queries.
I think that the find operation will execute only 2 queries then.
I would be happy if you try it.
https://github.com/chinpei215/cakephp-eager-loader
Usage
1. Enable EagerLoader plugin
// In your model
$actsAs = ['EagerLoader.EagerLoader'];
If you are afraid that loading my plugin breaks something somewhere, you can also enable it on the fly.
// On the fly
$this->Team->Behaviors->load('EagerLoader.EagerLoader');
2. Execute the same find operation
$this->Team->find('all', ['contain' => ['Player' => ['Skill']]]);
3. See the query log
You will see the query log such as the following:
SELECT ... FROM teams AS Team WHERE 1 = 1;
SELECT ... FROM players AS Player LEFT JOIN skills AS Skill ON Player.id = Skill.player_id WHERE Player.id IN ( ... );
if you feeling that query searching so many tables (ie, models) then
you can unbind those model, before performing search with find()
if you want to fetch some particular column of a table, then remove
others column by selecting "fields" in find().

Set and fetch bindModel query in cake template file

$categ = $this->FreeadsCategory->bindModel( array( 'hasMany' => array( 'Subcategory' => array('foreignKey' => 'category_id', 'order'=>'id ASC') ) ) );
$data = $this->FreeadsCategory->findById($i);
$this->set("datas", $data);
I am not able to fetch the datas in view page using cakephp
If i give pr($datas); showing nothing in ctp file
If i print the data in controller i am getting the following array structure
Array
(
[FreeadsCategory] => Array
(
[id] => 1
[uuid] => 51512434-e4c4-441b-b90e-16f8732d5573
[category] => Automobiles
[status] => Active
)
[Subcategory] => Array
(
[0] => Array
(
[id] => 1
[uuid] => 4ea15f22-adf0-4020-b35d1-052ff9ff9a27
[category_id] => 1
[subcategory] => Cars/Cabs/Jeeps
[status] => Active
)
[1] => Array
(
[id] => 5
[uuid] => 51cec363-e7ac-4095-a86b-0ccdf260d1b4
[category_id] => 1
[subcategory] => Buses/Lorries
[status] => Active
)
)
You don't fetch data in views, that violates the MVC pattern. Technically there are ways to do it but it's plain wrong, you'll end up with unmaintanable garbage code.
I really recommend you to get started by reading about the MVC design pattern and to do the CakePHP blog tutorial first to get a minimum of understanding of how CakePHP works.