Doctrine 2 native Query addFieldResult case sensitivity? - doctrine

i'm trying to figure out how to use Doctrin 2 nativeQuery.
I've created a simple staff class with the following attributes:
id (id)
userName (username)
lastName (last_name)
email (email)
note the camel cases. names in () are the names of the database fields. Not consisten and it's on purpose for testing.
when i try to use the native query i set up the following:
$rsm = new \Doctrine\ORM\Query\ResultSetMapping();
$rsm->addEntityResult('Entities\Staff', 's');
$rsm->addFieldResult('s', 'id', 'id');
$rsm->addFieldResult('s', 'userName', 'username');
$rsm->addFieldResult('s', 'lastName', 'last_name');
$rsm->addFieldResult('s', 'password', 'password');
$rsm->addFieldResult('s', 'email', 'email');
$sql = 'SELECT id, s.username, last_name, password, email from staff s ' ;
$query = $this->em->createNativeQuery($sql, $rsm);
$users = $query->getResult();
\Doctrine\Common\Util\Debug::dump($users[0]);
when i run the query i dump an object using the dump facility and get:
object(stdClass)#97 (10) { ["CLASS"]=> string(14) "Entities\Staff" ["id"]=> int(1) ["userName"]=> NULL ["firstName"]=> NULL ["lastName"]=> NULL ["password"]=> string(5) "admin" ["email"]=> string(12) "abc#druid.dk" ["isAdmin"]=> NULL ["conferences"]=> array(0) { } ["roles"]=> array(0) { } }
note how id, email and password contains correct values while userName and lastName are both NULL.
Why is that?
thanx for any help. i'm a bit confused. I don't see any examples like this in the Doctrine documentation so maybe i've misunderstood something. most probable... :)

Your parameters are switched around. Try this:
$rsm->addFieldResult('s', 'username', 'userName');
$rsm->addFieldResult('s', 'last_name', 'lastName');

Related

Cakephp 3 filter by a many to many associated relation

I have a users table, roles and users_roles as a join / pivot table. I am tryin to create a query to retrive all the users that HAVE NOT these roles: interventor, editor, chief
At the moment this is my query but I am not getting the desiered results, because users with these roles still coming.
$users = TableRegistry::getTableLocator()->get('Users');
$allUsers = $users->find('all', ['order' => ['Users.id ASC']])->select([
'id',
'name',
'surname',
])
->contain('Roles', function (Query $q) {
return $q
->select(['slug'])
->notMatching('Users.Roles', function ($q) {
return $q->where(['Roles.slug NOT IN' => ['interventor', 'editor', 'chief']]);
});
});
Thank you
Ok I found asolution.
Just adding an innerJoin to the query.
->innerJoinWith('Roles')->where(['Roles.slug NOT IN' => ['interventor', 'editor', 'chief']]);

Search users that follow user with eloquent

I got one page in table pages with:
id = 1, name, lastname
I got the table followers with these fields:
page_id, follower_id
And I got the table users, with these fields:
id, name, lastname, photo, friendly_url
I got 'search', what the user write, and the $id of the page:
public function u_followers_search($id) {
$_POST['search']
}
I want to search all the users that follow the page with the $_POST['search'] and show these users...
Followers::select('users.*')
->leftJoin('users', 'followers.follower_id', '==', 'user.id')
->where('page.id', $id )
->get();
Assuming your follower id is user.id (foreign key relation between followers table and users table).
With laravel elequent.
//Page.php
public function users()
{
return $this->hasManyThrough(
'App\User',
'App\Follower', // followers model
'page_id', // Foreign key in Follower
'id', // Foreign key in Users
'id', // Local key Page
'follower_id' // Local key Users
);
}
//Controller
public function u_followers_search(Request $request) {
$page = Page::find($request->id);
return $page->load([
'users' => function($query) use ($request){
$query->where('name', 'LIKE', '%'.$request->search.'%')
->orWhere('lastname', 'LIKE', '%'.$request->search.'%');
}
]);
}
Source: https://laravel.com/docs/5.6/eloquent-relationships#has-many-through

How to associate comments to users on Laravel?

public function store(Post $post)
{
$this->validate(request(), ['body' => 'required|min:2']);
$post->addComment(request('body'));
return back();
}
this is my code
I am having this error
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into comments (body, post_id, updated_at, created_at) values (ewrtyuttrew, 1, 2018-02-15 15:44:17, 2018-02-15 15:44:17))
You need to add a user who created the comment manually. For example:
public function addComment(string $body)
{
$this->comments()->create(['body' => $body, 'user_id' => auth()->id()]);
}
In your User model you can define the relationship as:
public function comments() {
return $this->hasMany(Comment::class);
}
So, if the user it's the logged user, then you can retrieve it with the Auth facade:
$user = Auth::user();
Then you can simply do:
$user->comments()->save(new Comment(request('body'));
Note that you must set the "fillable" fields on the Comment model in order to allow the dynamic creation.
Field 'user_id'
Open phpmyadmin and open comments table then after
Field 'user_id' => auto increment and primary key add
Try this I solve this type issues, thanks

Laravel 5.4 with Entrust: How to get users with roles

I am trying to get all users with roles, but "roles" field is always an empty array.
There are 4 users, 2 of them have at least 1 role attached, verified.
UserController.php
public function getUsers()
{
$users = User::select('name', 'email', 'type')->with('roles')->get();
return view('user.list', ['users' => $users, 'lang' => Lang::getLocale()]);
}
I get the 'roles' field as an empty array, even if I don't use "with->('roles')" in the controller. Weird?
If i print each user role in the view, I get this:
object(Illuminate\Database\Eloquent\Collection)#281 (1) { ["items":protected]=> array(0) { } }
What I am doing wrong?
You have to select also primary key, on which roles are related.
Eloquent is first selecting all users and then based on their IDS (primary and foreign) is selecting relations. If you dont select primary key, he cant relate relations.
$users = User::select('id', 'name', 'email', 'type')->with('roles')->get();
Also, if you want specifi which columns from roles you want, you have to select foreign key too.
$users = User::select('id', 'name', 'email', 'type')->with(['roles' => function ($query) {$query->select('id', 'name', 'user_id');}])->get();

Doctrine find() function is working but it is returning DQL first then the object. I don't want to display DQL

my code is
public function index() {
$user = $this->doctrine->em->find('user\models\User', 1);
echo '<br>';
echo $user->getName();
}
output is
SELECT t0.id AS id1, t0.name AS name2 FROM tbl_user t0 WHERE t0.id = ? array(1) { [0]=> int(1) } array(1) { [0]=> string(7) "integer" }
john
I have used CodeIgniter 2.2.2 and I have integrated doctrine using these steps link
I finally solved the problem. I had to comment the EchoSQLLogger() in Doctrine.php file in the libraries folder.
// Set up logger
//$logger = new EchoSQLLogger;
//$config->setSQLLogger($logger);

Resources