I have next pivot table:
Schema::create('coach_user', function(Blueprint $table)
{
$table->integer('coach_id')->unsigned()->index();
$table->foreign('coach_id')->references('id')->on('coaches')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->tinyInteger('rank');
});
In User.php:
public function coaches()
{
return $this->belongsToMany(\App\Coach::class)->withPivot('rank');
}
How I can receive coaches of user with some rank? Something like this:
$user->coaches->where('rank',1)->get().
use wherePivot() to filter the results returned by belongsToMany.
$user->coaches()->wherePivot('rank',1)->get();
Use wherePivot for pivot columns and relation as method:
$user->coaches()->wherePivot('rank',1)->get().
Related
I want to create a student with some courses.
This is the Laravel view
I created two different tables: a students table
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('student_name');
$table->string('first_name');
$table->string('last_name');
$table->string('email');
});
}
and a courses table.
public function up()
{
Schema::create('student_courses', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('student_id');
$table->string('course_name');
$table->timestamps();
});
}
The students table creates the information of the student and saves it in the student table.
I want to save the courses into the courses table, with the student id. They should have a One to Many relationship. How can I save the different courses into the courses table with the id of the specific student?
You can't store course name in student courses table. You need to create separate tables for courses. After that you can use foreign key for store both the data of student and courses into the student_courses table as per below.
public function up()
{
Schema::create('student_courses', function (Blueprint $table) {
$table->id();
$table->integer('student_id')->unsigned()->nullable();
$table->foreign('student_id')->references('id')->on('students')->onDelete('cascade');
$table->integer('course_id')->unsigned()->nullable();
$table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
$table->timestamps();
});
}
Hope this will helps you.
First create Relationship:
In User Model Create:
public function courses(){
return $this->hasMany(Course::class);
}
In Course Model Create:
public function students(){
return $this->belongsTo(Studnet::class);
}
Now in your save function:
$course = new Course($request->all());
$user->courses()->save($course);
I have a films table which contains a many to many relation e.g AgeRatings with a pivot table called film_age_rating which contains a film_id as a foreign key I have this with 3 other relations too.
Right now my app has no functionality to make a deletion request to remove a film, so right now I hard delete rows in the films DB table. When I delete a film from the films table it deletes items, but the data within the pivot table remains unchanged which I don't want to happen.
films_table
public function up()
{
Schema::create('films', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name')->nullable();
}
film_age_rating
public function up()
{
Schema::create('film_age_ratings', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('age_rating_id');
$table->uuid('film_id');
$table->timestamps();
});
}
Film Model
public function ageRatings(): BelongsToMany
{
return $this->belongsToMany(
AgeRatings::class,
'film_age_rating',
'film_id',
'age_rating_id'
);
}
Age Rating Model
public function film(): BelongsToMany
{
return $this->belongsToMany(
Film::class,
'film_age_rating',
'age_rating_id',
'film_id'
);
}
I know an option is to add an onDelete cascade to the pivot tables, but that will require lots of migration tables. Is there another way to tackle this without adding a DELETE request for now or is adding the cascade the only option?
Could you please advise me on the most efficient option?
The only way I can imagine is to use softDeletes
On this way, there will be only one query to delete a film, and it will be a logical delete.
You can delete data using the sync() method. It releases the relation from the pivot table. I assuming that you want to delete a film. So this is a sample method in your controller.
public function deleteFilm($id)
{
$film = Film::find($id);
$film->ageRatings()->sync([]);
$film->delete();
}
So I am trying to figure a solution to this but not sure exactly how to do this. I have a table that stores all the shows that happen. In a given show I can have multiple providers attend that show. A provider could also attend many shows as well. So how do I store this in the DB and do the eloquent relationship?
Show Schema
Schema::create('shows', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('number')->unsigned();
$table->dateTime('airDate');
$table->string('podcastUrl')->nullable();
$table->timestamps();
});
Provider Schema
Schema::create('providers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('shortName')->nullable();
$table->string('image')->nullable();
$table->string('social')->nullable();
$table->timestamps();
});
Would I store the provider_id in the shows schema?
Update 1
So I created a new migration for a pivot table
Schema::create('provider_show', function (Blueprint $table) {
$table->integer('provider_id')->unsigned()->index();
$table->foreign('provider_id')->references('id')->on('providers')->onDelete('cascade');
$table->integer('show_id')->unsigned()->index();
$table->foreign('show_id')->references('id')->on('shows')->onDelete('cascade');
$table->primary(['provider_id', 'show_id']);
});
Then in the show model I created the following
public function providers()
{
return $this->belongsToMany(Provider::class);
}
Now when I am saving a new show I added a multiselect to select the providers I want
$show = new Show;
$show->name = $request->name;
$show->number = $request->number;
$show->airDate = $request->airDate;
$show->podcastUrl = $request->podcastUrl;
$show->providers()->attach($request->providerList);
$show->save();
Session::flash('message', "Created Successfully!");
return back();
Then when I save I get the following error
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: provider_show.show_id (SQL: insert into "provider_show" ("provider_id", "show_id") select 1 as "provider_id", as "show_id" union all select 2 as "provider_id", as "show_id")
Create a provider_show migration which will act as your pivot table.
This table would contain both provider_id and show_id which will provide the many-to-many relationship between those entities.
Then on your Provider model you can provide a shows() method which returns a BelongsToMany relationship.
// In your Provider model
public function shows()
{
return $this->belongsToMany('App\Show');
}
Note that Laravel by default looks for a pivot table name based alphabetically on the two relationships.
You can also add the inverse on your Show model by providing a providers() method that also returns a BelongsToMany relationship.
I have a User model which belongsToMany() Conferences. Conferences hasMany Users, also a m:m relationship.
I am working on a link() method in my ConferencesController, but I'm not sure how to go about.
I collect the given Conference by id, and the Auth::check-ed User. How do I add the conference and user into the pivot table?
create a pivot table
//conference_user
Schema::create('conference_user', function(Blueprint $table) {
$table->increments('id');
$table->integer('conference_id')->unsigned()->index();
$table->foreign('conference_id')->references('id')->on('conferences');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
now in User model, add this method
public function conferences()
{
return $this->belongsToMany('Conference','conference_user');
}
and in Conference model, add this method
public function users()
{
return $this->belongsToMany('User','conference_user');
}
now in your controller, you can use something like this
$conferences=$user->conferences;
or
$users=$conference->users;
i have four tables in database:
users (for storing user details)
conversations (for storing conversations id).
conversationsmember (for storing conversations member)
conversationsreply (for storing conversations reply)
A user will have many conversations and each conversation will have its members and replies.
here are the details:
Users migration:
$table->increments('id');
$table->string('name', 32);
$table->string('username', 32);
$table->string('email', 320);
$table->string('password', 64);
$table->timestamps();
Conversations migration:
$table->increments('id');
$table->timestamps();
conversationsmembers migration:
$table->increments('id');
$table->integer('conversation_id');
$table->integer('user_id');
$table->timestamps();
conversationsreply migrations
$table->increments('id');
$table->integer('conversation_id');
$table->integer('user_id');
$table->timestamps();
Now in User model, i need to define relationship between users table and conversations table. As they are not directly connected, i used hasManyThrough relation.
..app/models/User.php
...
public function conversations()
{
return $this->hasManyThrough('Conversation', 'ConversationsMember', 'conversation_id', 'id');
}
...
When i 'm trying to use it, it's showing a blank array.
I would try a belongsToMany relationship, where conversationsmembers is your pivot table.
public function conversations()
{
return $this->belongsToMany('Conversation', 'conversationsmembers');
}
You may also want to define the inverse of the relationship in your Conversation model:
public function users()
{
return $this->belongsToMany('User', 'conversationsmembers');
}
I'm a bit confuse about your migration so I'm not sure that's what you want.