I have 3 models: User, Role, Tool where each user could have many roles, and each role could have many tools.
The many to many relationships work well in each case. I can access:
User::find(1)->roles
Tool::find(1)->roles
Role::find(1)->tools
Role::find(1)->users
My tables are:
users
id
name
roles
id
name
tools
is
name
role_user
id
role_id
user_id
role_tool
id
role_id
tool_id
In each model:
//In User Model
public function roles()
{
return $this->belongsToMany('Rol');
}
//In Role Model
public function users()
{
return $this->belongsToMany('User');
}
public function tools()
{
return $this->belongsToMany('Tool');
}
//In Tool Model
public function roles()
{
return $this->belongsToMany('Rol');
}
I need to get all the tools of a single user like: User::find(1)->roles()->tools. How can I do that?
Get all the roles of the user, then in a loop you get all tools of the role and merge them to an array where you store all tools.
$tools = array();
foreach(User::find(1)->roles as $role)
$tools = array_merge($tools, $role->tools->toArray());
This runs a query for every iteration, so for better performance you should use eager loading.
$tools = array();
foreach (User::find(1)->load('roles.tools')->roles as $role) {
$tools = array_merge($tools, $role->tools->toArray());
}
Now you can place this to a function called tools() in your User model.
public function tools()
{
$tools = array();
foreach ($this->load('roles.tools')->roles as $role) {
$tools = array_merge($tools, $role->tools->toArray());
}
return $tools;
}
You can call it like this: User::find(1)->tools().
I don't think that the framework has a better solution. One other method is to use the Fluent Query Builder and create your own query but I don't see how that would be better.
Define a hasManyThrough relationship in User::find(1)->roles()->tools
class User extends Eloquent {
public function tools()
{
return $this->hasManyThrough('Tool', 'Role');
}
}
Then you can access straight forward:
$user->tools
Related
I have three db tables. The first is PROJEKTS, the second table is USERS, and the third table is ACTIVITIES. The tables are related. There are multiple users under each project, and there are activities under each user.
A similar project is addressed here: Laravel Eloquent Relationships on 3 tables
I need Laravel Controller. Load only one specific project with users where each user can have activities.
class Projekts extends Model
{
public function user()
{
return $this->hasMany('App\User');
}
}
class User extends Authenticatable
{
public function activity()
{
return $this->hasMany('App\Activities');
}
}
Use this:
$projekt = Projekts::with('user.activity')->find($id);
foreach($projekt->user as $user) {
foreach($user->activity as $activity) {
}
}
This works for me. I want to know if there is a simpler code.
$form = $request->all();
$newproject = \App\Projects::create( $form );
$newproject_Id = $newproject->id;
foreach ($form['items'] as $item) {
$user= new \App\User;
$user->projects_id = $novafaktura_Id;
$user->nic = $item['name'];
$user-> ...and other
$user->save();
}
I'd like to establish a many to many polymorphic relation in Laravel. (I'm new to it)
A user can have many profile types
Profile types are like Admin, Webmaster, ProjectManager.
I created a polymorphic relation and a pivot table for the profiles.
class User {
public function profiles(){
return Profile::where('user_id', $this->id);
}
}
class Webmaster { // and class Admin, Projectmanager
public function profiled(){
return $this->morphToMany(Profile::class, 'profileable');
}
public function saveToUser($user)
{
$profile = new Profile;
$profile->user_id = $user->id;
return $this->profiled()->save($profile);
}
}
Now I can save the models to the corresponding User.
$projectManager->saveToUser($user);
$webmaster->saveToUser($user);
It gets all saved to the pivot table as expected and the relations are valid.
profiles table looks like this:
id
user_id
profilable_id
profilable_type
Now the problem is retrieving a model collection of my profiles. I get the Profile types, but I dont get the Webmaster and ProjectManager.
So the question is: how do I get this model collection in this example?
Your model structure is going to be like:
class Webmaster extends Model
{
public function users()
{
return $this->morphToMany('App\Profile', 'userable');
}
}
class Admin extends Model
{
public function users()
{
return $this->morphToMany('App\Profile', 'userable');
}
}
// and ProjectManager, ....
User Model:
class User extends Model
{
public function webmasters()
{
return $this->morphedByMany('App\Webmaster', 'userable');
}
public function admins()
{
return $this->morphedByMany('App\Admin', 'userable');
}
}
Database schema:
webmasters
id - integer
...
admins
id - integer
...
users
id - integer
...
userables
user_id - integer
userable_id - integer
userable_type - string
Now, you can retrieve the relations:
$webmaster = App\Webmaster::find(1);
// retrieve users of a profile
foreach ($webmaster->users as $user) {
//
}
$user = App\User::find(1);
// retrieve webmaster profiles of a user
foreach ($user->webmasters as $webmasters) {
//
}
Actually, your profiles (webmaster, admin, projectmanager) are userable.
Hypothetical situation: Let's say we have 3 models:
User
Role
Permission
Let's also say User has a many-to-many relation with Role, and Role has a many-to-many relation with Permission.
So their models might look something like this. (I kept them brief on purpose.)
class User
{
public function roles() {
return $this->belongsToMany(Role::class);
}
}
class Role
{
public function users() {
return $this->belongsToMany(User::class);
}
public function permissions() {
return $this->belongsToMany(Permission::class);
}
}
class Permission
{
public function roles() {
return $this->belongsToMany(Role::class);
}
}
What if you wanted to get all the Permissions for a User? There isn't a BelongsToManyThrough.
It seems as though you are sort of stuck doing something that doesn't feel quite right and doesn't work with things like User::with('permissions') or User::has('permissions').
class User
{
public function permissions() {
$permissions = [];
foreach ($this->roles as $role) {
foreach ($role->permissions as $permission) {
$permissions = array_merge($permissions, $permission);
}
}
return $permissions;
}
}
This example is, just one example, don't read too much into it. The point is, how can you define a custom relationship? Another example could be the relationship between a facebook comment and the author's mother. Weird, I know, but hopefully you get the idea. Custom Relationships. How?
In my mind, a good solution would be for that relationship to be described in a similar way to how describe any other relationship in Laravel. Something that returns an Eloquent Relation.
class User
{
public function permissions() {
return $this->customRelation(Permission::class, ...);
}
}
Does something like this already exist?
The closest thing to a solution was what #biship posted in the comments. Where you would manually modify the properties of an existing Relation. This might work well in some scenarios. Really, it may be the right solution in some cases. However, I found I was having to strip down all of the constraints added by the Relation and manually add any new constraints I needed.
My thinking is this... If you're going to be stripping down the constraints each time so that the Relation is just "bare". Why not make a custom Relation that doesn't add any constraints itself and takes a Closure to help facilitate adding constraints?
Solution
Something like this seems to be working well for me. At least, this is the basic concept:
class Custom extends Relation
{
protected $baseConstraints;
public function __construct(Builder $query, Model $parent, Closure $baseConstraints)
{
$this->baseConstraints = $baseConstraints;
parent::__construct($query, $parent);
}
public function addConstraints()
{
call_user_func($this->baseConstraints, $this);
}
public function addEagerConstraints(array $models)
{
// not implemented yet
}
public function initRelation(array $models, $relation)
{
// not implemented yet
}
public function match(array $models, Collection $results, $relation)
{
// not implemented yet
}
public function getResults()
{
return $this->get();
}
}
The methods not implemented yet are used for eager loading and must be declared as they are abstract. I haven't that far yet. :)
And a trait to make this new Custom Relation easier to use.
trait HasCustomRelations
{
public function custom($related, Closure $baseConstraints)
{
$instance = new $related;
$query = $instance->newQuery();
return new Custom($query, $this, $baseConstraints);
}
}
Usage
// app/User.php
class User
{
use HasCustomRelations;
public function permissions()
{
return $this->custom(Permission::class, function ($relation) {
$relation->getQuery()
// join the pivot table for permission and roles
->join('permission_role', 'permission_role.permission_id', '=', 'permissions.id')
// join the pivot table for users and roles
->join('role_user', 'role_user.role_id', '=', 'permission_role.role_id')
// for this user
->where('role_user.user_id', $this->id);
});
}
}
// app/Permission.php
class Permission
{
use HasCustomRelations;
public function users()
{
return $this->custom(User::class, function ($relation) {
$relation->getQuery()
// join the pivot table for users and roles
->join('role_user', 'role_user.user_id', '=', 'users.id')
// join the pivot table for permission and roles
->join('permission_role', 'permission_role.role_id', '=', 'role_user.role_id')
// for this permission
->where('permission_role.permission_id', $this->id);
});
}
}
You could now do all the normal stuff for relations without having to query in-between relations first.
Github
I went a ahead and put all this on Github just in case there are more people who are interested in something like this. This is still sort of a science experiment in my opinion. But, hey, we can figure this out together. :)
Have you looked into the hasManyThrough relationship that Laravel offers?
Laravel HasManyThrough
It should help you retrieve all the permissions for a user.
I believe this concept already exists. You may choose on using Laravel ACL Roles and Permissions or Gate, or a package known as Entrust by zizaco.
Zizaco - Entrust
Laracast - watch video 13 and 14
Good luck!
I am trying to grasp the concept of Eloquent ORM by creating a ticketing system at the moment. What I am trying to achieve is:
The tickets with the user who posted the ticket
The feedback belonging to the ticket and the user who entered the
feedback
This is what I have right now:
// TicketController.php
public function index()
{
$tickets = Ticket::with('feedback')->with('user')->orderBy("created_at", "desc")->get();
//dd($tickets);
return View::make('modules.helpdesk.index')->withTickets($tickets);
}
And the following models
// Ticket.php
class Ticket extends Eloquent {
protected $table = 'helpdesk_tickets';
public function feedback()
{
return $this->hasMany('Feedback');
}
public function user()
{
return $this->belongsTo('User');
}
}
// Feedback.php
class Feedback extends Eloquent {
protected $table = 'helpdesk_tickets_feedback';
public function ticket()
{
return $this->belongsTo('Ticket');
}
}
// User.php
class User extends Eloquent {
protected $table = 'users';
public function ticket()
{
return $this->belongsTo('Ticket');
}
}
What I have now is the tickets, their related feedback and user who created the ticket. What I am trying to achieve now is to also get the user who created the feedback.
You need to fix the relation:
// User model
public function tickets()
{
return $this->hasMany('Ticket'); // adjust namespace if needed
}
Next add the relation:
// Feedback model
public function user()
{
return $this->belongsTo('User'); // namespace like above
}
then use eager loading:
// it will execute 4 queries:
// 1st for tickets
// 2nd for feedback
// 3rd for feedbacks' user
// 4th for tickets' user
$tickets = Ticket::with('feedback.user', 'user')->latest()->get();
you can then access the relations in a loop, like below:
#foreach ($tickets as $ticket)
{{ $ticket->title }} by {{ $ticket->user->name }}
#foreach ($ticket->feedback as $feedback)
{{ $feedback->content }}
#endforeach
#endforeach
What you want to do is create nested relations, just like Ticket add a belgonsTo relation on feeback
When you want to use it you can chain relations using the dot notation feedback.user
The code
// Feedback.php
class Feedback extends Eloquent {
protected $table = 'helpdesk_tickets_feedback';
public function ticket()
{
return $this->belongsTo('Ticket');
}
public function user()
{
return $this->belgonsTo('User')
}
}
// TicketController.php
public function index()
{
$tickets = Ticket::with('feedback')->with('user')->with('feedback.user')->orderBy("created_at", "desc")->get();
//dd($tickets);
return View::make('modules.helpdesk.index')->withTickets($tickets);
}
EDIT:
Even though this would work, it will execute more queries than needed. See Jareks answer.
Original Answer:
First of all you need to get your relationships straightened, in User.php you should call the user relationship with HasMany.
public function ticket() {
return $this->hasMany('Ticket');
}
In modules.helpdesk.index you should now have a Ticket Collection since your attaching the $ticket variable to the view.
If you loop through this collection with a foreach loop then what you should get is a model each loop:
foreach($tickets as $ticket) {
// Prints the name property of the Ticket model
print $ticket->name;
// Since a ticket only belongs to ONE user then that means that you are trying to fetch a model
// What we're doing here is getting the User model via the relationship you made in the model Ticket.php and then getting the name.
print $ticket->user()->first()->username;
// Since a ticket can have MANY feedbacks that means were fetching a collection
// which needs to be broken down to models so we do that looping the collection.
// Here we are doing the same thing as with the User model except with a collection.
foreach($ticket->feedback()->get() as $feedback) {
$feedback->text;
}
}
You should definitely check out the Laravel API and see Collection and Model there. http://laravel.com/api/ You get alot of help from there when you get stuck, trust me :)
I hope this answered your question.
I'm trying to tease out a logical problem that I'm having and I didn't know where else to ask!
I have two Objects whose relationship I'm trying to describe; the User and the Game. So, right now, I have that a User belongs to many Games, and that a Game belongs to many Users. What I'm trying to describe is the special instance when a User owns a Game. Presumably, this would simply be a column in the table for the owner_id. I am, however, struggling to establish how I can represent this in Eloquent. Do I need to create a new Object for the Game owner? Or can I use some kind of User role to describe this?
Game
class Game extends Eloquent
{
protected $guarded = array();
public static $rules = array();
// Game belongsToMany User
public function users()
{
return $this->belongsToMany('User');
}
// Need to identify the owner user.
}
User
class User extends Eloquent
{
protected $guarded = array();
public static $rules = array();
// User belongsToMany Game
public function games()
{
return $this->belongsToMany('Game');
}
}
I'm having difficulty even figuring out how to ask this in a clear and concise way, so if there's any more detail needed, please don't hesitate to ask.
What you need is thid table: games_owners. This is a migration schema for it:
Schema::create('games_owners', function($table)
{
$table->increments('id');
$table->integer('user_id');
$table->integer('game_id');
$table->timestamps();
});
This would be your User model:
class User extends Eloquent
{
protected $guarded = array();
public static $rules = array();
// User belongsToMany Game
public function games()
{
return $this->belongsToMany('Game', 'games_owners', 'user_id');
}
}
And you game model:
class Game extends Eloquent
{
protected $guarded = array();
public static $rules = array();
// Game belongsToMany User
public function users()
{
return $this->belongsToMany('User', 'games_owners', 'game_id');
}
// Need to identify the owner user.
}
And then you'll be able to do things like this:
$user = User::find(1);
foreach($user->games as $game) {
echo $game->name;
}