In my DB I have a project table which has
project
id | title | users |
1 | First | 1,2,3 |
2 | Second| 2,6 |
how can I check Yii::app()->user->id contained in users field? I want to check, if true then show row in gridview.
Which $criteria must I use?
Use LIKE query for checking your user id exist or not in users column.
$user = Yii::app()->user->id;
$result = Yii::app()->db->createCommand('SELECT * FROM project WHERE users LIKE "%'.$user.'%"')->queryAll();
if(count($result)){
//Your other scripts to show in grid view
}
If you have a Project model class then you also can use:
$user = Yii::app()->user->id;
$criteria = new CDbCriteria;
$criteria->select = '*';
$criteria->compare('t.users', $user, true);
$results = Project::model()->findAll($criteria);
Related
I'm creating a one-on-one chat, but there are two columns: user 1 and user 2.
The user may be in user 1 or user 2, and I want to show him or her the chats from people who have contacted him or him, but the table returned as
and I just want to retrieve the other user id not the authenticated user, who is 51
so l want to select either user 1 or user 2 which has the other user id.
the code I implemented
$room = Chat::where([
['user_1',Auth::id()]
])->orWhere([
['user_2',Auth::id()]
])->latest()->get();
// dd($room);
return view('users.chats',[
'room_id'=>$room,
// 'messages'=>Message::oldest()->where('chat_id',$room->chat_id)->get(),
'selectedUser' => false
]);
How can I create a new column called "other user" and only retrieve the other user's ID?
Running it through php on array filter fixed the problem.
$room = Chat::where([
['user_1',Auth::id()]
])->orWhere([
['user_2',Auth::id()]
])->latest()->get();
$users = array();
foreach($room as $item){
array_push($users,$item->user_1,$item->user_2);
}
$fillterdUsers = array_filter($users,function($val){
return $val !== auth()->id();
});
return view('users.chats',[
'room_id'=>$fillterdUsers,
// 'messages'=>Message::oldest()->where('chat_id',$room->chat_id)->get(),
'selectedUser' => false
]);
Sorry for the fuorviant title but I'll trying to explain what I'm try to do. So, I've two table ea_users and ea_user_settings.
ea_users - STRUCTURE
id | data|
5 | 0
ea_user_settings - STRUCTURE
|id | username|
5 Sandokan
Now what I'm trying to do is validate if certain username already exists in the system. The table ea_users contain the id, that rapresents the id of a single user, and the data field (0 user not removed, also 1 user deleted).
In the ea_user_settings table I've all settings of my users. Now a possible idea for check if a certain username already exist is this:
public function validate_username($username, $user_id)
{
$num_rows = $this->db->get_where('ea_user_settings',
array('username' => $username, 'id_users <> ' => $user_id))->num_rows();
return ($num_rows > 0) ? FALSE : TRUE;
}
This function have two parameters: username and user_id, the username that's going to be inserted and the user_id (if this is valorized means that I'm actually stay update the user so I don't need to check on it row if the username already exists).
Actually all working good but I want to check if the username exists for only the user with the data equal to 0, if the data is 1 the username is available 'cause it's deleted. I don't know if the situation is more clear. How I can achieve that in a single query?
You can try something like this
public function validate_username($username, $user_id)
{
$num_rows =
$this->db->select('*')
->from('ea_user_settings')
->join('ea_users', 'ea_user_settings.id_users = ea_users.id', 'left')
->where(array('ea_user_settings.username' => $username, 'ea_user_settings.id_users <> ' => $user_id, 'ea_users.data' => 1))
->get();
return ($num_rows->num_rows() > 0) ? 'We have this username and it was deleted!' : 'This username was not deleted';
}
I'm new to Phalcon and would like to create a PHP web-service on my WAMP server. I have a table called "coreswings" in MySQL database and it represents the cores and wings of a large building. There are five fields: abbr, name, type, busyFrom, busyTo.
Following the tutorial on http://docs.phalconphp.com/en/latest/reference/tutorial-rest.html , I can route my requests to my desired functions, but the phql, "SELECT * FROM coreswings", doesn't work and returns me fatal errors.
index.php
<?php
/*###########################################################################
########## Set up connection to be used by model CoresWings, start ##########
###########################################################################*/
// use Loader() to autoload the model
$loader = new \Phalcon\Loader();
$loader->registerDirs(array(__DIR__.'/models/'))->register();
$di = new \Phalcon\DI\FactoryDefault();
// set up the database service
$di->set('db', function(){
return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => "localhost",
"username" => "user",
"password" => "user_pw",
"dbname" => "map"
));
});
// create and bind the DI to the application
$app = new \Phalcon\Mvc\Micro($di);
/*#########################################################################
########## Set up connection to be used by model CoresWings, end ##########
#########################################################################*/
/*#########################################################
########## create routes according to api, start ##########
#########################################################*/
// get all cores and wings
$app->get('/coresWings', function() use ($app){
$phql = "SELECT * FROM coreswings";
$coresWings = $app->modelsManager->executeQuery($phql);
$data = array();
foreach($coresWings as $coreWing){
$data[] = array(
'abbr' => $coreWing->abbr,
'name' => $coreWing->name,
'type' => $coreWing->type,
'busyFrom' => $coreWing->busyFrom,
'busyTo' => $coreWing->busyTo,
);
}
echo json_encode($data);
});
// testing purpose
$app->get('/testing', function(){
$data = array(
'function' => 'tesing',
'data' => '001'
);
echo json_encode($data);
});
/*#######################################################
########## create routes according to api, end ##########
#######################################################*/
$app->handle();
?>
When I access the URL http://localhost/FYP/001/api/coresWings, the following errors are shown:
( ! ) Fatal error: Uncaught exception 'Phalcon\Mvc\Model\Exception' with message 'Table "cores_wings"
doesn't exist on database when dumping meta-data for CoresWings' in
D:\Program Files\wamp\www\FYP\001\api\index.php on line 39
( ! ) Phalcon\Mvc\Model\Exception: Table "cores_wings" doesn't exist on database when dumping meta-data for CoresWings in D:\Program Files\wamp\www\FYP\001\api\index.php on line 39
Of course I don't have a table called "cores_wings", but my phql is "SELECT * FROM coreswings". Please tell me if I have done anything wrong. Thanks so much.
#
mysql> describe coreswings;
+----------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------------------+------+-----+---------+-------+
| abbr | varchar(63) | NO | PRI | NULL | |
| name | varchar(1024) | YES | | NULL | |
| type | enum('core','wing') | NO | | NULL | |
| busyFrom | time | YES | | NULL | |
| busyTo | time | YES | | NULL | |
+----------+---------------------+------+-----+---------+-------+
Model: CoresWings.php
use Phalcon\Mvc\Model,
Phalcon\Mvc\Model\Message,
Phalcon\Mvc\Model\Validator\InclusionIn,
Phalcon\Mvc\Model\Validator\Uniqueness;
class CoresWings extends Model{
public function validation(){
// building type must be "core" or "wing"
$this->validate(new InclusionIn(
array(
"field" => "type",
"domain" => array("core", "wing")
)
));
// building abbreviation must be unique
$this->validate(new Uniqueness(
array(
"field" => "abbr",
"message" => "Abbreviation of a building must be unique"
)
));
// check if any messages have been produced
if($this->validationHasFailed()==true){
return false;
}
}
}
?>
If you want minimal configuration then you should follow some PhalconPHP's conventions.
One of them is that it for CamelCaseModel PhalconPHP uses camel_case table.
If you want to set different tabel for model then you should set it's source:
class CoresWings extends Model{
public function initialize() {
$this->setSource('coreswings');
}
}
You can use Phalcon\Mvc\Model::getSource() method. It is table name map with manual.
I have two tables
User:
id | name | gender(boolean)
Gender:
gender_id (boolean) | gender_name (text)
I want to display the text representation of gender through DataProvider
UserController:
public function actionIndex()
{
$crt = new CDbCriteria();
$crt->alias = 'so';
$crt->select = 'so.id, so.name, so.gender, fl.Gender_name';
$crt->join = " left join " . Gender::model()->tableName() . " as fl on fl.Gender_id = so.Gender";
$dataProvider=new CActiveDataProvider('User', array('criteria' => $crt));
$this->render('index',array(dataProvider'=>$dataProvider,));
}
As a result, I can not pass through dataProvider table gender
You can beter create a relation in the models. This way you dont have to use the criteria, and the value canbe accessed through $model->gender->gender_name for example
Is there a simple way of adding custom fields to a model? Say I have a table "user" with 3 fields: id, name and surname. I want this:
$user = User::model()->findByPk(1);
$echo $user->fullName; // echoes name and surname
Please note: I want this custom field to be added via sql, smth like
$c = new CDbCriteria();
$c->select = 'CONCAT("user".name, "user".surname) as fullName';
$user = User::model()->find($c);
Problem is that fullName property is not set.
UPD:
here is the code for a little bit trickier problem -- custom field from another table. This is how it's done:
$model = Application::model();
$model->getMetaData()->columns = array_merge($model->getMetaData()->columns, array('fullName' => 'CONCAT("u".name, "u".surname)'));
$c = new CDbCriteria();
$c->select = 'CONCAT("u".name, "u".surname) as fullName';
$c->join = ' left join "user" "u" on "t".responsible_manager_id = "u".id';
$model->getDbCriteria()->mergeWith($c);
foreach ($model->findAll() as $o) {
echo '<pre>';
print_r($o->fullName);
echo '</pre>';
}
You can add a function to the User class:
public function getFullName() { return $this->name.' '.$this->surname; }
This will return the full name as if it were an attribute from the database. This is much easier than adding a calculated column to the SQL.
In model
public function getMetaData(){
$data = parent::getMetaData();
$data->columns['fullName'] = array('name' => 'fullName');
return $data;
}
Thus not recommended