conditions doesn't work on hasMany association using contain in cakephp 3 - cakephp-3.0

I am trying to search on several conditions on Users Model and Addresses Model. Here Addresses Model are associated with Users Model in hasMany relation. Any condition on Users Model working fine but not working in Addresses Model. Here is my code snippet.
$this->hasMany('Addresses', [
'foreignKey' => 'user_id',
'joinType' => 'LEFT'
]);
$this->belongsTo('Users', [
'foreignKey' => 'user_id'
]);
$options = array();
$status = $this->request->getQuery('status');
$options = array_merge(array('Users.status' => $status), $options);
$profile = array();
$phone = $this->request->getQuery('phone');
$profile = array_merge(array('Addresses.phone' => $phone), $profile);
$addressArr = array('Addresses.user_id', 'Addresses.mobile', 'Addresses.phone', 'Addresses.country_id', 'Addresses.state_id', 'Addresses.city', 'Addresses.zipcode', 'Addresses.address_line1');
$uses = $this->find('all')
->select(['Users.id', 'Users.user_type_id', 'Users.first_name', 'Users.last_name', 'Users.email', 'Users.image', 'Users.status', 'Users.social_type'])
->contain([
'Addresses' => function ($q) use ($addressArr, $profile) {
return $q->select($addressArr)->where($profile);
}
])
->where($options)
->offset($offset)
->limit($limit)
->toArray();
return $uses;

Related

API Create Multiple Input Laravel

I'm currently creating API for multiple inputs using laravel. The data will be stored into two tables : Order and Detail_Order. One order can have many detail orders.
But now, the data only stored into Order table, and got an error: ErrorException: Invalid argument supplied for foreach() in file. Does anyone know how? Thank you.
Here's my code :
public function createDetail($total_passenger, $id_trip, $id_users, Request $request){
$trip = Trip::where(['id_trip' => $id_trip])->get();
$seat = $request->id_seat;
if(Detail_Order::where(['id_trip' => $id_trip, 'id_seat' => $seat])
->where('status', '!=', 5)
->exists()) {
return $this->error("Seat has been booked");
}else{
$order = new Order();
$order_select = Order::select('id_order');
$order_count = $order_select->count();
if ($order_count === 0) {
$order->id_order = 'P1';
}else{
$lastrow=$order_select->orderBy('created_at','desc')->first();
$lastrow_id = explode('P', $lastrow->id_order);
$new_id = $lastrow_id[1]+1;
$order->id_order = 'P'.$new_id;
}
$order->id_trip = $id_trip;
$order->id_users = $id_users;
$order->date_order = date('Y-m-d H:i:s');
$order->id_users_operator = 'O4';
$order->save();
foreach($request->passenger_name as $key => $value){
Detail_Order::create([
'id_trip' => $order->id_trip,
'id_seat' => $request->id_seat[$key],
'id_order' => $order->id_order,
'passenger_name' => $request->passenger_name[$key],
'gender' => $request->gender[$key],
'departure' => $request->departure[$key],
'destination' => $request->destination[$key],
'phone' => $request->phone[$key],
'status' => 1
]);
}
return response()->json([
'status' => true,
'message' => "Successfully saved data",
'data' => $order
]);
}

Inserting variables in Yii2 to Database

I am trying to insert $product, $pric and $user to database table cart. Following is the function that I have created in SiteController.php.
public function actionCartadd($id)
{
$product = Additem::find()
->select('product')
->where(['id' => $id])
->one();
$pric = Additem::find()
->select('price')
->where(['id' => $id])
->one();
$user = Yii::$app->user->identity->username;
$connection = Yii::$app->getDb();
$result = Yii::$app->db->createCommand()
->insert('cart', [
'product' => '$product',
'price' => '$pric',
'user' => '$user',
])->execute();
if ($result)
return $this->render('custstore');
}
However, this end up in error. Can anyone suggest any fix
Try this following code
$result = Yii::$app->db->createCommand()->insert('cart', [
'product' => $product->product,
'price' => $pric->price,
'user' => $user
])->execute();
Look at this fragment:
'product' => '$product',
'price' => '$pric',
'user' => '$user',
Use double quotes in values or just variables without quotes
Also, better way to fetch product and price:
$productItem = Additem::findOne($id);
if ($productItem instanceof Additem) {
$product = $productItem->product;
$pric = $productItem->price;
}

Insert or update in laravel?

What would be the best way to set this query? i can't seem to find any documentation on an actual insert or update that works, I'm hoping to do it via the Eloquent model but can't seem to get it working
any help would be appreciated.
DB::table('questions')->insert([
'marital_status' => $request->marital_status,
'job_title' => $request->job_Title,
'industry' => $request->industry,
'occupation' => $request->occupation,
'paye' => $request->paye,
'self_employed' => $request->self_employed,
'child_benefit' => $request->child_benefit,
'work_home' => $request->work_home,
'own_transport' => $request->own_transport,
'company_vehicle' => $request->company_vehicle,
'annual_income' => $request->annual_income,
'pay_memberships' => $request->pay_memberships,
'income_benefits' => $request->income_benefits,
'printer' => $request->printer,
'contact' => $request->contact,
'share' => $request->share,
'terms' => $request->terms,
'user_id' => $user
]);
here is my Model for Questions
<?php
namespace App;
class Questions extends Model
{
protected $fillable = [
'marital_status',
'job_title',
'industry',
'occupation',
'paye',
'self_employed',
'child_benefit',
'work_home',
'own_transport',
'company_vehicle',
'annual_income',
'pay_memberships',
'income_benefits',
'printer',
'contact',
'share',
'terms',
'user_id'
];
public function users(){
return $this->hasOne('App\User');
}
}
Use Eloquent with mass assignment:
Question::updateOrCreate($request->all()->put('user_id', $user));
Or:
$question = Question::firstOrNew('some_id', $someId);
$question->fill($request->all()->put('user_id', $user))->save();
Don't forget to fill $fillable array with all properties you want to persist:
class Question extends Model
{
protected $fillable = [
'marital_status',
'job_title',
'industry',
'occupation',
'paye',
'self_employed',
'child_benefit',
'work_home',
'own_transport',
'company_vehicle',
'annual_income',
'pay_memberships',
'income_benefits',
'printer',
'contact',
'share',
'terms',
'user_id'
]
Update
If put() method doesn't work for some reason, try this:
$request->merge(['user_id' => $user]);
And then just use $request->all()
Or:
$requestData = $request->all();
$requestData['user_id'] = $user;
And then use $requestData

How to choose the fields from a associated model at find

Before I had this:
//ArticlesController::index
$articles = $this->Articles->find('all', [
'contain' => ['Comments']
]);
So I set the fields key:
//ArticlesController::index
$articles = $this->Articles->find('all', [
'fields' => ['title', 'text],
'contain' => ['Comments']
]);
Since I set the fields key the result of the find is not bringing the comments anymore.
$articles = $this->Articles->find('all')
->select(['fields_you_want_from_Articles'])
->contain(['Comments' => function($q) {
return $q
->select(['fields_you_want_from_Comments']);
}]);

CakePHP find Queries with aliases SQLSTATE[42S22] Error

I'm having a weird problem with my relationships/aliases in CakePHP and now its preventing me from accessing my data correctly.
I have:
User hasMany CreatorModule (alias for Module)
User HABTM LearnerModule (alias for Module)
Module belongsTo Creator (alias for User)
Module HABTM Learner (alias for User)
And I'm trying to call:
$id = $this->Module->User->findByEmail($email);
$modules = $this->Module->findByUserId($id['User']['id']);
The queries that get generated aren't correct - the table-alias is wrong. I'm not sure which of the above is responsible but I get:
SELECT
`Creator`.`id`,
`Creator`.`email`,
`Creator`.`organization`,
`Creator`.`name`,
`Creator`.`password`,
`Creator`.`verified`,
`Creator`.`vcode`
FROM
`snurpdco_cake`.`users` AS `Creator`
WHERE
`User`.`email` = 'foo#example.com' # <--
LIMIT 1
I figured out that the error is that CakePHP should change 'User' in the WHERE clause to Creator, but doesn't, even if I use the alias. How do I complete this query correctly.
Further, as a related problem, I find that I can no longer use User in my model calls etc now that I have defined aliases. Is there a way around this?
EDIT: As requested, here is my model code defining the aliases:
class User extends AppModel {
public $name = 'User';
public $uses = 'users';
public $hasMany = array(
'OwnedModule' => array(
'className' => 'Module',
'foreignKey' => 'user_id',
'dependent' => true
));
public $hasAndBelongsToMany = array(
'LearnerModule' => array(
'className' => 'Module',
'joinTable' => 'modules_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'module_id',
'unique' => 'keepExisting',
));
//The rest of the Model
}
//Different file, condensed here for spacing
class Module extends AppModel {
public $name = 'Module';
public $belongsTo = array(
'Creator' => array(
'className' => 'User'));
public $hasAndBelongsToMany = array(
'Learner' => array(
'className' => 'User',
'joinTable' => 'modules_users',
'foreignKey' => 'module_id',
'associationForeignKey' => 'user_id',
'unique' => 'keepExisting',
));
//The rest of the Model
}
try
$id = $this->Module->Creator->find('first',
array('conditions' => array('Creator.email' => $email)
);
$modules = $this->Module->findByCreatorId($id['User']['id']);