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
Related
I'm experiencing the following:
Goal: I would like to list all partners and the categories they belong to. Basically, it's a many to many relationship.
Below is the code:
Partner Categories Table Migration
public function up()
{
Schema::create('partcats', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('partcatnameP')->unique();
$table->unsignedBigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
Partners Table Migration
public function up()
{
Schema::create('partners', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('partnername');
$table->string('regnumber')->unique();
$table->unsignedBigInteger('activestatus_id')->unsigned();
$table->foreign('activestatus_id')->references('id')->on('activestatuses');
$table->unsignedBigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
Partner_Category Migration
public function up()
{
Schema::create('partner_partcat', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('partner_id')->unsigned();
$table->foreign('partner_id')->references('id')->on('partners')->onDelete('cascade');
$table->unsignedBigInteger('partcat_id')->unsigned();
$table->foreign('partcat_id')->references('id')->on('partcats')->onDelete('cascade');
$table->timestamps();
});
}
Models are as shown below:
Partcat Model
public function partners()
{
return $this->belongsToMany('App\Partcat','partner_partcat');
}
Partner Model
public function partcats()
{
return $this->belongsToMany('App\Partcat','partner_partcat');
}
and the Partners Controller is as shown below:
public function index()
{
//
$partners = Partner::all()->partcats();
// dd(Partner::all()->partcats());
return view('partners.index',['partners'=>$partners]);
}
This is where I'm trying to retrieve the list of partners and its related categories. However, I get a BadMethod call error.
You can use the following method
$partners = Partner::with('partcats')->get();
https://laravel.com/docs/5.6/eloquent-relationships#eager-loading
A many to many pivot table typically has the id for both tables it is relating.
The Partner_Category migration you have posted only seems to contain a partner_id. You may need to add in the category_id.
public function up()
{
Schema::create('partner_partcat', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('partner_id')->unsigned();
$table->unsignedBigInteger('partcat_id')->unsigned();
$table->timestamps();
$table->foreign('partner_id')->references('id')->on('partners')->onDelete('cascade');
$table->foreign('partcat_id')->references('id')->on('partcats')->onDelete('cascade');
});
}
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.
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
I have a question about how to generate a query with eloquent and I would appreciate any help from you.
I have 4 tables in my database:
1. modules
2. roles
3. module_rol (pivot table)
4. regions
Structure of the tables:
modules:
id int
name string
region int
active bool
roles
id int
name string
module_rol
rol_id int
module_id int
regions
id int
name string
I need to get all the values from the modules table with some conditions for example ..
public function getUserModules($rol, $region)
{
// Return all modules to which that role is allowed to access and have that region defined
}
While waiting for some help, thank you very much in advance
EDIT 1:
Schema::create('regions', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('modules', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('region')->unsigned();
$table->boolean('active')->default(true);
$table->timestamps();
$table->foreign('region')
->references('id')->on('regions')
->onDelete('cascade');
});
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('module_rol', function (Blueprint $table) {
$table->increments('id');
$table->integer('rol_id');
$table->integer('module_id');
$table->timestamps();
$table->foreign('rol_id')
->references('id')->on('roles')
->onDelete('cascade');
$table->foreign('module_id')
->references('id')->on('modules')
->onDelete('cascade');
});
You need to define ManyToMany relationship between Module and Role using pivot table
Module Model
public function roles(){
return $this->belongsToMany(Role::class, 'module_rol');
}
public function region(){
return $this->belongsTo(Region::class, 'region');
}
Role Model
public function modules(){
return $this->belongsToMany(Module::class, 'module_rol');
}
Fetch Data
public function getUserModules($role, $region)
{
// Return all modules to which that role is allowed to access and have that region defined
$modules = Module::where('region', $region->id)
->whereHas(['roles' => function($query) use ($role) {
return $query->where('role_id', $role->id)
}])->get();
return $modules;
}
Details https://laravel.com/docs/5.6/eloquent-relationships#many-to-many
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?