Yii2 - get with multiple tables - yii

I have 5 tables I need to join in order to get all users for the team. Tables are:
User: iduser | firstName | lastName
Team: idteam | name
TeamUser: idteamuser | idteam | iduser
Portal: idportal | name
PortalTeam: idportalteam | idteam
In the Portal model I need to get all users for that portal. Is this possible?

I think there is a missing field (idportalteam) in Portal Model to link to other Models. When this is added you can create a relation for all models.
Portal:
public function getPortalTeam()
{
return $this->hasOne(PortalTeam::className(), ['idportalteam' => 'idportalteam']);
}
PortalTeam:
public function getTeamUser()
{
return $this->hasOne(TeamUser::className(), ['idteam' => 'idteam']);
}
TeamUser:
public function getTeam()
{
return $this->hasOne(Team::className(), ['idteam' => 'idteam']);
}
TeamUser:
public function getUser()
{
return $this->hasOne(User::className(), ['iduser' => 'iduser']);
}
To get the models from Portal use:
$portal = (new Portal())->findOne(xyz);
$team = (($portal->portalTeam)->teamUser)->team;
$user = (($portal->portalTeam)->teamUser)->user;

Not the -best- answer but can use ActiveQuery object and the join() method.
http://www.yiiframework.com/doc-2.0/yii-db-query.html#join()-detail
Exp:
$data = \Portal::find()
->join($type, $table, $on = '', $params = [])
->andWhere([/* ... */])
->all();

Related

NHibernate 5.1 ManyToOne - delete orphan not working as expected

I have following entities:
public class Person {
public int Id {get;set;}
public String Name {get;set;}
public Passport Passport {get;set;}
}
public class Passport {
public int Id {get;set;}
public String PassportNo {get;set;}
// ... other properties
}
and following mapping (for Person):
ManyToOne(x => x.Passport, m =>
{
m.Column("PassportId");
m.Lazy(LazyRelation.NoLazy);
m.Unique(true);
m.Cascade(Cascade.All | Cascade.DeleteOrphans);
});
DB schema:
Table Person:
Id | Name | PassportId
Table Passport:
Id | PassportNo | other props.
As we can see, Person has it's passport, but passport has no idea about its owner, which is behaviour I want. There are 2 more assumptions:
Person can have only 1 passport at a time
Passport can NOT exists without person
Problem is, when I assign new Passport to a Person, the old Passport remains in DB.
person.Passport = new Passport() { PassportNo = "AB 123456" };
// ...
session.Flush();
session.Commit();
SQL queries that are generated are INSERT and UPDATE (inserts new Passport, and updates Person with new Passport) - however there is no DELETE on orphaned, old passport.
The workaround I found is to set current Passport to null, call session.Flush(), and assign new Passport, like this:
person.Passport = null;
session.Flush();
person.Passport = new Passport() { PassportNo = "AB 123456" };
// ...
session.Flush();
session.Commit();
however IMO it is a hacky solution.
So, summing it up:
am I missing something in my mapping?
is above behaviour a bug in NH?
can it be solved without hacky Flush()?
After long searching for solution, I found that there is a Join mapping, which perfectly fits above scenario.
Hope it helps someone.
More info here:
http://notherdev.blogspot.com/2012/01/mapping-by-code-join.html

Laravel Eloquent populates collection with id 1 always

I have a project on laravel 5.
I wrote an SQL to select games from database, and after executing it, I got models collection, where every model has id = 1.
This is my query:
select * from `games` left join `game_vendors` on `games`.`vendor_id` =
`game_vendors`.`id` where `game_vendors`.`name` != 'some_vendor' and
`games`.`id` not in (1,2,3,4,5,6,7,8,9,10,11,12);
checked this query in mysql terminal - all is fine, id's are correct, but on postman or in the browser, I got this
array(2021) {
[0]=>
array(32) {
["id"] => int(1)
[1]=>
array(32) {
["id"] => int(1)
...
...
...
[24]=>
array(32) {
["id"] => int(1)
Model class contains this:
class Game extends Model {
protected $table = 'games';
public function vendor()
{
return $this->hasOne('App\GameVendor', 'vendor_id', 'id');
}
Use Laravel Eloquent Relationship and "WHERE NOT IN"
Update Model as
class Game extends Model {
protected $table = 'games';
public function vendor()
{
return $this->hasOne('App\GameVendor', 'vendor_id', 'id')->where('name', '!=' ,'some_vendor');
}
And use Eloquent as
$games = Game::whereNotIn('id',[1,2,3,4,5,6,7,8,9,10,11,12])->get();
foreach($games as $game){
$game->vendor->name
}

Laravel 4 - Auth::attempt() not working and returns FALSE

I've installed Laravel 4.2 but ran into a problem where the 'Auth::attempt()' function is not willing to let the user in but I can log in with the 'Auth::loginUsingId()' function.
My User model
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
public $timestamps = false;
protected $table = 'user';
protected $primaryKey = 'user_id';
protected $hidden = array('user_pass', 'remember_token');
public function getAuthIdentifier(){
return $this->getKey();
}
public function getAuthPassword(){
return $this->user_pass;
}
public function getRememberToken(){
return $this->user_remembertoken;
}
public function setRememberToken($value){
$this->user_remembertoken = $value;
}
public function getRememberTokenName(){
return "user_remembertoken";
}
public function getReminderEmail(){
return $this->user_email;
}
}
My routes (I've put in some exaple)
Route::get('login', function(){
$user = 'dd';
$pass = '123456';
$credentials =["user_nickname" => "dd","user_pass" => "123456"];
if(Auth::attempt($credentials)){
echo 'Login Successful';
}
else{
echo 'Login Failed';
}
});
Route::get('check', function()
{
if(Auth::check()){echo 'identified';}
else{echo 'not identified';}
return;
});
Route::get('reg', function()
{
$user = new User;
$user->user_nickname = 'dd';
$user->user_pass = Hash::make('123456');
$user->user_realname = 'dd';
$user->user_email = 'test#gmail.com';
$user->user_accesslevel = 1;
$user->user_language = 'HU';
$user->save();
});
Route::get('forcelogin', function()
{
Auth::loginUsingId(6,TRUE);
return;
});
My Database
user_id | smaillint
user_nickname | varchar(25)
user_pass | char(60)
user_email | varchar(255)
user_realname | varchar(60)
user_accesslevel | tinyint(3)
user_language | char(2)
user_regdate | timestamp
user_remembertoken | char(60)
The user password column MUST BE 'password'. This is hard coded into Laravel and is not configurable (even with the getAuthPassword() function).
So change your database migration from
user_pass | char(60)
to
password | varchar(60)
and change
$user->user_pass = Hash::make('123456');
to
$user->password = Hash::make('123456');
when registering the user and it will work.
Change user password column field from char(60) to "varchar 255" delete user password hash recreate it and give it a try!

Edit profile page with 3 tables - Yii frameworks

I am new on Yii framework, so please i need some help where to start.
What i need is, action and module to display a form to a user, which his will be able to edit is own profile (with profile picture), so i have 3 table
user_account || user_personal || user_general
how can i build a form that insert and update those 3 table at once?
i try this:
This is what i did, but its still not saving the data even into 1 table.
public function actionUpdate() {
$model = new ProfileUpdate();
if(isset($_POST['ProfileUpdate']))
{
$model->attributes = $_POST['ProfileUpdate'];
if($model->validate())
{
$account = new Profile();
$account->userid = Yii::app()->user->id;
$account->name = $model->name;
$account->website = $model->website;
$account->category = $model->category;
$account->save();
$this->redirect('profile');
}
}
model:
class Profile extends CActiveRecord
{
public $userid;
public $name;
public $website;
public $category;
public static function model()
{
return parent::model(__CLASS__);
}
public function tableName()
{
return 'userinfo';
}
public function primaryKey()
{
return 'id';
}
public static function userExists($user)
{
return self::model()->countByAttributes( array('username'=>$user) ) > 0;
}
}
You can use all three models in a single function
for example:
In create function
$model_account = new user_account;
$model_personal= new user_personal;
$model_general = new user_general;
$this->render('create',array(
'model_account'=>$model_account, 'model_personal' => $model_personal, 'model_general' => $model_general
));
here the all three models pass by render to create page.
in form page you can use the every model attributes as fields
Like this
echo $form->textField($model_account,'account_name');
echo $form->textField($model_personal,'email');
echo $form->textField($model_general,'address');
In create function / Update function
$model_account->attributes = $_POST['user_account'];
$model_personal->attributes = $_POST['user_personal'];
$model_general->attributes = $_POST['user_general'];
if($model_account->validate() && $model_personal->validate() && $model_general->validate())
{
$model_account->save();
$model_personal->save();
$model_general->save();
}

Laravel 4 user authentication

I am doing a simple login and i am facing small problem, just can't figure out what's the problem.
Here is my auth.php :
<?php
return array(
/*
|--------------------------------------------------------------------------
| Default Authentication Driver
|--------------------------------------------------------------------------
|
| This option controls the authentication driver that will be utilized.
| This driver manages the retrieval and authentication of the users
| attempting to get access to protected areas of your application.
|
| Supported: "database", "eloquent"
|
*/
'driver' => 'eloquent',
/*
|--------------------------------------------------------------------------
| Authentication Model
|--------------------------------------------------------------------------
|
| When using the "Eloquent" authentication driver, we need to know which
| Eloquent model should be used to retrieve your users. Of course, it
| is often just the "User" model but you may use whatever you like.
|
*/
'model' => 'Login',
/*
|--------------------------------------------------------------------------
| Authentication Table
|--------------------------------------------------------------------------
|
| When using the "Database" authentication driver, we need to know which
| table should be used to retrieve your users. We have chosen a basic
| default value but you may easily change it to any table you like.
|
*/
'table' => 'tbl_user',
/*
|--------------------------------------------------------------------------
| Password Reminder Settings
|--------------------------------------------------------------------------
|
| Here you may set the settings for password reminders, including a view
| that should be used as your password reminder e-mail. You will also
| be able to set the name of the table that holds the reset tokens.
|
| The "expire" time is the number of minutes that the reminder should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
As you can see above, i am using my own model Login and my own table tbl_user
Below is my model (Login.php)
<?php
class Login extends Eloquent {
protected $table = "tbl_user";
public static function checkUser($array)
{
$data = DB::table('tbl_user')->where('user_email', $array['user_email'])->where('user_password', $array['user_password'])->get();
return $data;
}
}
Now i think there is something wrong with the model, i just don't know what it is. I am moving from CodeIgniter to Laravel 4 and this auth thingy is new for me.
Here is the route :
Route::post('login', function(){
$userdata = array(
'user_email' => Input::get('email'),
'user_password' => Hash::make(input::get('password'))
);
if(Auth::attempt($userdata)){
echo "Login Success!";
}else{
echo "Login Failed!";
}
});
I am getting Login Failed! password is hashed! Hurmm! Any suggestion?
Auth uses a user model which implements the Userinterface, if you want to create your own custom User model you should implement the UserInterface, you can check the deault provided user model in your app:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
As Petkostas mentioned, you have to implements UserInterface, RemindableInterface.
In addition, Fix this line as well:
$userdata = array(
'user_email' => Input::get('email'),
'user_password' => Hash::make(input::get('password')) // no need to hash password
);
No need to hash password before Auth::attempt() as Laravel will do it for you.
I have removed Hash::make() from code:
$userdata = array(
'user_email' => Input::get('email'),
'user_password' => input::get('password')
);
if(Auth::attempt($userdata)){
echo "Login Success!";
}else{
echo "Login Failed!";
}