How to get model through many-to-many relationship in Laravel - laravel

I've got the following situation in Laravel, simply visualize by the following:
task -([many-to-many]- task_user -[many-to-many])- user -[one-to-one]- info
I'm able to get from task to user, but unfortunately I can not get to info.
Does anyone have an idea what I'm missing?
Model: task
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
public $table = "tasks";
public function taskuser(){
//task->task_user->user->info
return $this->belongsToMany(User::class,'task_user');
}
when I add ->belongsTo(Info::class) to the function taskuser I get the following error:
Illuminate\Database\Eloquent\RelationNotFoundException
Call to undefined relationship [taskuser] on model [App\Models\Task].
I'm definitely missing something but what?
EDIT: Info model works with user as User->info give the correct results
Model User:
public function info()
{
return $this->hasOne('App\Models\Info');
}
EDIT: Controller
$task= Task::whereBetween('datetime',array($start,$end))->with('tasktype','taskuser')->get();
EDIT: relevant tables
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username');
$table->rememberToken();
$table->timestamps();
Schema::create('infos', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned(); //internal id
$table->string('name');
#foreign references
$table->foreign('user_id')->references('id')->on('users');
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->integer('task_types_id')->unsigned();
$table->string('title');
$table->datetime('datetime');
$table->integer('length');
$table->string('description')->nullable();
$table->integer('updated_by')->unsigned();
$table->timestamps();
#foreign references
$table->foreign('task_types_id')->references('id')->on('task_types');
$table->foreign('updated_by')->references('id')->on('users');
Schema::create('task_users', function (Blueprint $table) {
$table->integer('task_id')->unsigned();
$table->integer('user_id')->unsigned();
#foreign references
$table->foreign('task_id')->references('id')->on('tasks');
$table->foreign('user_id')->references('id')->on('users');

By reading more of the Laravel documentation, specifically https://laravel.com/docs/6.x/eloquent-relationships#eager-loading
adding .info
$task= Task::whereBetween('datetime',array($start,$end))
->with('tasktype','taskuser.info')
->get();
Now it works.

Related

Laravel get data from pivot table many to many relationship

Tables with relationship
I want to get the classes for specific notes. Here note id and class id are in a pivot table.
Note.php
public function classes()
{
return $this->belongsToMany(MyClass::class);
}
MyClass.php
public function notes()
{
return $this->belongsToMany(Note::class);
}
I am saving the data successfully by
$note->classes()->attach($request->class);
MyClass Migration
Schema::create('my_classes', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
$table->boolean('isDeleted')->default(false);
$table->dateTime('deletedAt')->nullable();
});
Notes Migration
Schema::create('notes', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('description')->nullable();
$table->string('image')->nullable();
$table->timestamps();
$table->boolean('isDeleted')->default(false);
$table->dateTime('deletedAt')->nullable();
});
my_class_note migration
Schema::create('my_class_note', function (Blueprint $table) {
$table->bigIncrements('id');
$table->foreignId('my_class_id')->constrained();
$table->foreignId('note_id')->constrained();
$table->timestamps();
});
Needed help on getting classes for a specific note. One note can have many classes.
You can simply access it by using the relationship property, there always will be if you have defined a relationship.
// returns a collection of classes
$classes = Note::find(1)->classes;
In your controller.
return view('yourview', ['classes' => $classes]);
In your view.
#foreach($classes as $class)
<p>{{$class->name}}</p>
#endforeach

Laravel, pivot table conflicts with many-to-many relationship

Hey guys so I'm using spatie binary uuid package and I had few doubts
Things done so far:
User.php Migration:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->uuid('uuid');
$table->primary('uuid');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Role migration just have basic field called "name" with timestamps
Pivot table: role_user
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('role_id')->unsigned()->nullable()->index();
$table->uuid('user_uuid');
});
}
I know this is terribly wrong and I don't know what to do, I'm trying to save the Role model via this call
$uuid = '478d7068-ae64-11e8-a665-2c600cf6267b';
$model = User::withUuid($uuid)->first();
$model->roles()->save(new Role(['name' => 'Admin']));
it doesn't work, where am I going wrong? I think it has something to do with role_user migration
User.php
public function roles()
{
return $this->belongsToMany(Role::class);
}
try this, pivot migration:
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('role_id')->unsigned()->nullable()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->uuid('user_uuid');
$table->foreign('user_uuid')->references('uuid')->on('users')->onDelete('cascade');
});
}
roles relation:
public function roles(){
return $this->belongsToMany(Role::class,'role_user','user_uuid','role_id');
}
please let me know if it didn't work
you should edit your relation to this
return $this->belongsToMany(Role::class,'role_user','user_uuid','role_id');
if you say about your error we better can help you

Laravel relationship error in migration

I am trying to make two tables relationship in laravel. But i can't understand why i'm getting error "errno: 150 "Foreign key constraint is incorrectly formed"". please check my migration code below.
items table
public function up()
{
Schema::create('items', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->string('name');
$table->decimal('price',5,2);
$table->integer('count_left')->default(0);
$table->timestamps();
$table->foreign('category_id')->references('id')->on('categories');
});
}
categories
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
}

Relationship between Users, Settings, Setting_types Eloquent Laravel 5.4*

How would you go to create a relationship between the folowing tables:
Users table:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('firstname');
$table->string('surename');
$table->string('address')->nullable();
$table->string('city')->nullable();
$table->string('country')->nullable();
$table->string('postcode')->nullable();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Setting_type table:
Schema::create('setting_types', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Settings table:
Schema::create('settings', function (Blueprint $table) {
$table->increments('id');
$table->string('value');
$table->timestamps();
});
Setting_type_user table:
Schema::create('setting_type_user', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->integer('type_id')->unsigned();
$table->integer('setting_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('type_id')->references('id')->on('setting_types');
$table->foreign('setting_id')->references('id')->on('settings');
$table->timestamps();
});
This is the result I want to get:
{"id":1,"value":"578943205.jpg","created_at":"2017-07-18 00:00:00","updated_at":null,"pivot":{"setting_id":1,"user_id":1,"type_id":1}}
It depends on many things, but it looks like you want to use many-to-many relationship here.
First, in settings pibot table change it to:
$table->unsignedInteger('user_id');
$table->unsignedInteger('type_id');
It's also a good idea to add foreign key constraints to the table:
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('type_id')->references('id')->on('setting_types');
Then define belongsToMany() relationship in both User and SettingType models. Since you don't follow naming conventions, you have to define foreign keys manually. In the User model:
public function settingTypes()
{
return $this->belongsToMany('App\SettingType', 'settings', 'user_id', 'type_id');
}
And in the SettingType model:
public function users()
{
return $this->belongsToMany('App\User', 'settings', 'type_id', 'user_id');
}

Additional fields on polymorphic many to many table map to Eloquent model

I'm trying to create a ploymorphic many-to-many relationship that also includes an additional relationship. I can't seem to figure out how to get Eloquent to map the additional field to a model.
I have projects, users on those projects, and project roles that dictate permissions for that user on the project.
My tables:
Schema::create('projects', function(Blueprint $table){
$table->increments('id');
$table->timestamps();
$table->softDeletes();
$table->string('name');
$table->integer('possessor_id');
$table->string('possessor_type');
});
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->softDeletes();
$table->string('email');
$table->string('name');
$table->string('username');
});
Schema::create('project_accessors', function(Blueprint $table){
$table->increments('id');
$table->timestamps();
$table->integer('project_id')->unsigned();
$table->foreign('project_id')->references('id')->on('projects');
$table->integer('project_role_id')->unsigned();
$table->foreign('project_role_id')->references('id')->on('project_roles');
$table->integer('entity_id')->unsigned();
$table->string('entity_type');
});
Schema::create('project_roles', function(Blueprint $table){
$table->increments('id');
$table->timestamps();
$table->softDeletes();
$table->string('name');
$table->string('permissions');
$table->integer('project_id')->unsigned();
$table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
});
I define projects on users like this:
public function projects()
{
return $this->morphToMany('App\Project', 'entity', 'project_accessors')->withTimestamps()->withPivot('project_role_id');
}
I define users and roles on projects like this:
public function roles()
{
return $this->hasMany('App\ProjectRole');
}
public function users()
{
return $this->morphedByMany('App\User', 'entity', 'project_accessors')->withTimestamps()->withPivot('project_role_id');
}
Is there a way to map project_role_id to an actual instance of my Project Role model?

Resources