I have tables: users, resources and pivot table user_resources.
users
id
username
etc.
resources
id
resource_name
etc.
user_resources
id
user_id
resource_id
User model:
class Resources extends Eloquent {
public function users() {
return $this->belongsToMany('User', 'user_resources');
}
}
and resource model:
class User extends Eloquent {
public function resources() {
return $this->belongsToMany('Resource', 'user_resources');
}
}
How can I get all of the users and all of the resources that belongs to the users.
Probably you just have to:
$everything = User::with('resources')->get();
Related
I have a database setup where you have a lecturer having many groups and each group having many students and also a student can be in many groups. Therefore I have a one to many relationship between a lecturer and groups (respectively) and a many to many relationship between students and groups.
I want to show the lecturer how many students they have overall. For example if the lecturer has 5 groups with 5 students in each then I want to show 25. I tried this auth()->user()->userable->groups()->withCount('students') but I got this:
Call to a member function getRelationExistenceCountQuery() on null
Edited, Here are the relationships:
# user model
class User extends Authenticatable{
public function userable(){
return $this->morphTo();
}
}
# staff/lecturer model
Staff extends Model {
public function user(){
return $this->morphOne(User::class, 'userable');
}
public function groups(){
return $this->hasMany(Group::class);
}
}
#group model
class Group extends Model {
public function staff(){
return $this->belongsTo(Staff::class);
}
public function students(){
$this->belongsToMany(Student::class, 'groups_students', 'group_id');
}
}
# student model
class Student extends Model {
public function groups(){
return $this->belongsToMany(Group::class, 'groups_students', 'student_id');
}
}
What's the most efficient way to get my desired result?
Group::students() is missing the return statement:
public function students(){
return $this->belongsToMany(Student::class, 'groups_students', 'group_id');
^^^^^^
}
You can get the total of number of students like this:
$groups = auth()->user()->userable->groups()->withCount('students')->pluck('students_count');
$count = $groups->sum();
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.
I have the following model relationships. If a user logs in as an employee, I want them to be able to get a list of employees for a their company and the roles they have been assigned:
class User {
// A user can be of an employee user type
public function employee()
{
return $this->hasOne('App\Employee');
}
//
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
class Employee {
// employee profile belong to a user
public function user()
{
return $this->belongsTo('App\User');
}
// employee belongs to a company
public function company()
{
return $this->belongsTo('App\Company');
}
}
class Company {
public function employees()
{
return $this->hasMany('App\Employee');
}
}
But the following query doesnt work. I get error Column not found: 1054 Unknown column companies.id in WHERE clause:
$employee = Auth::user()->employee;
$companyEmployees = Company::with(['employees.user.roles' => function ($query) use ($employee) {
$query->where('companies.id', '=', $employee->company_id)
->orderBy('users.created_at', 'desc');
}])->get();
The users and the employees table have a one to one relationship.
All employees have a base role type of employee in addition they may also have other roles such as manager, supervisor etc.
How do I write a query that gives me a company with all its employees and their roles?
I've tried to add a hasManyThrough relation to the Company model but that doesn't work either?
public function users()
{
return $this->hasManyThrough('App\User', 'App\Employee');
}
I think you're ring to get a list of coworkers for the current user and eager load the user and role?
$employee = Auth::user()->employee;
$companyEmployees = Company::with(['employees.user.roles')->find($employee->company_id);
Or perhaps:
$companyEmployees = Company::find($employee->company_id)->employees()->with('user.roles')->get();
$sorted = $companyEmployees->sortBy(function($employee){ return $employee->user->created_at; });
That might be a more direct route. Is your employee id in the user table or vice versa? The eloquent relationships are easy to set backwards.
Users::select('table_users.id')->with('roles')->join('table_employes', function($join) use ($employee) {
$join->on('table_employes.user_id','=','table_users.id')->where('table_employes.company_id', '=', $employee->company_id);
})->orderBy('tables_users.created_at')->get();
1. Create relationship for database table columns in migrtaion :
User Role
$table->foreign('user_id')->references('id')->on('users');
Users
$table->increments('id');
2. Create a model for each database table to define relationship
User.php (model)
public function userRoles()
{
return $this->hasOne('App\UserRoles', 'user_id', 'id');
}
Userroles.php (model)
public function user()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
3. Let controller handle database calls recommended to use REST api
Controller
use App\User;
use App\UserRoles;
class UserController extends Controller
{
public function index()
{
return User::with('userRoles')->orderBy('users.created_at', 'desc')->paginate(50);
}
}
I have 3 tabels: users, teachers And posts.
users:
id - integer
name - string
teachers:
id - integer
teacher_id - integer
user_id - integer
name - string
posts:
id - integer
user_id - integer
title - string
User Model:
class User extends Model
{
public function teachers()
{
return $this->hasMany('App\Teacher');
}
}
Teacher Model:
class Teacher extends Model
{
public function posts()
{
return $this->hasMany('App\Post', 'user_id','teacher_id');
}
}
? Question is How can I use sth like this:
$user = User::find(1);
$teacher_posts = $user->teachers()->posts
I'm sort of new to laravel but here is my take.
What I have realized is that typically your many to many relationships will require a pivot table.
users:(id, name)
teachers:(id, teacher_id, name)
teacher_users:(id, user_id, teacher_id)
posts:(id, user_id, title)
And your Eloquent models will look like this.
class User extends Model
{
public function teachers()
{
return $this->belongsToMany('App\Teacher');
}
public function posts()
{
return $this->hasMany('App\Post');
}
}
class Teacher extends Model
{
public function users()
{
return $this->belongsToMany('App\User');
}
}
$user = User::find(1);
$user_posts = $user->posts();
Check out the documentation here for more details
I'm writing a survey with Laravel 4 and need the ability for users to be able to take the same survey multiple times (and have their answers saved as different instances.)
I currently have a pivot table called survey_user that links a user to an invited survey. A potentially positive side effect of the pivot table is that its primary key could be used to have unique survey instances.
My problem is figuring out how to get answers, specifically through the user model. Answers table would contain a foreign key to the primary of the pivot table.
My User model:
class User extends Eloquent {
public function surveys() {
return $this->belongsToMany('Survey', 'survey_user')
->withPivot('id', 'completed_at');
}
public function answers() {
// This should return all of the user's answers, irrespective of
// survey id's.
}
}
Tables:
surveys: id
users: id
survey_user: id, survey_id, user_id, completed_at
answers: survey_user_id, answer_text, ...
How might I accomplish this psuedo-relationship or perhaps a better way to structure?
Use relationships! Here's how I would do it:
class User extends Eloquent {
public function surveys() {
return $this->belongsToMany('Survey');
}
public function answers() {
return $this->hasMany('Answer');
}
}
class Survey extends Eloquent {
public function surveys() {
return $this->belongsToMany('User');
}
public function answers() {
return $this->hasMany('Answer');
}
}
class Answer extends Eloquent {
public function survey() {
return $this->belongsTo('Survey');
}
public function user() {
return $this->belongsTo('User');
}
}