How to seed a separate table with foreign keys in Laravel - php

I have three tables with genres, movies and their relationship. I want to create a seed for the relationship table but don't really know how to do it exactly so the genre_id and movie_id would have the same number id. Here's the migration for the genres:
public function up()
{
Schema::create('genres', function (Blueprint $table) {
$table->id();
$table->string('name');
});
}
Movies:
public function up()
{
Schema::create('movies', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('status')->nullable()->default(0);
$table->string('image_path')->default('images/default.png');
});
}
Relationship:
public function up()
{
Schema::create('genre_movie', function (Blueprint $table) {
$table->foreignId('genre_id')->constrained();
$table->foreignId('movie_id')->constrained();
});
}
Here's the movie model:
class Movie extends Model
{
use HasFactory;
protected $fillable = ['name', 'status', 'image_path'];
public function genres()
{
return $this->belongsToMany(Menu::class, 'genre_movie');
}
}
Here's the genre model:
class Genre extends Model
{
use HasFactory;
protected $fillable = ['name'];
public function movies()
{
return $this->belongsToMany(Movie::class, 'genre_movie');
}
}

Seed your genres and movies tables initially, then you can use those to seed your genre_movie table. So for example:
// Seed 10 genres
Genere::factory(10)->create();
// Seed 50 movies
Movie::factory(50)->create();
// Seed some relationships
foreach (Genre::all() as $genre) {
$movies = Movie::inRandomOrder()->take(random_int(1, Movie::count())->get();
$genre->movies()->attach($movies);
}
Update 1
is there a way to control how many records its gonna create for the genre_movie table?
Yup.
$movies = Movie::inRandomOrder()->take(10)->get();
Altering the parameter value provided to take(x) will define how many records are created in the genre_movie table for each Genre. In the above example it will create 10 records per Genre. That could be set to two with take(2) etc.
Alternatively you could always just grab the first() Movie record if you just want a single Movie per Genre in your genre_movie table.
$movies = Movie::inRandomOrder()->first();

Related

Use foreign key id to get a foreign table name

I have some tables, all estate have an category_id, I put a foreign key to do the relationship, but won't work now, How can I list my estate with the equivalent category name
Category Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
protected $fillable = ['name'];
public function estate()
{
return $this->belongsTo('App\Estate');
}
}
Estate Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Estate extends Model
{
protected $table = 'estates';
protected $fillable = ['categories_id'];
public function category()
{
return $this->hasMany('App\Category');
}
}
Create Estate table
Schema::create('estates', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->string('name');
$table->string('estate_photo')->nullable(true);
$table->double('value');
$table->integer('label_id');
});
Create Category table
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
Add category foreign key to estate
Schema::table('estates', function (Blueprint $table) {
$table->unsignedBigInteger('categories_id');
$table->unsignedBigInteger('sub_categories_id');
$table->foreign('categories_id')->references('id')->on('categories');
$table->foreign('sub_categories_id')->references('id')->on('sub_categories');
});
My object have not foreign key data to get $object->categories_id->name
According to your models, you have to use :
// get all estates for the example
$estates = Estate::get();
foreach ($estates as $estate) {
// use the name of the relation to get your category - first
dump($etate->category[0]->name);
// or to get all categories
foreach ($etate->category as $category) {
dump($category->name);
}
}
I'm sure this would work .. correct me if I'm wrong
Estate::with('category')->get();
It will bring back all the estates, each one with its categories attached.

BelongsTo in Laravel

I have a table which is named cars with 2 fields id, matriculation.
Then, I have another table which is named series with 2 fields id, name.
I have created my fk_serie on my table cars.
public function up()
{
Schema::create('cars', function (Blueprint $table) {
$table->increments('id');
$table->string('matriculation', 25);
$table->integer('fk_serie')->unsigned();
$table->foreign('fk_serie')->references('id_serie')->on('serie');
$table->timestamps();
});
}
Here is my information about the table series.
public function up()
{
Schema::create('series', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 30);
$table->timestamps();
});
}
In my model, I only have a function on the model Car.
public function serie(){
return $this->belongsTo('App\Serie', 'fk_serie');
}
I don't have nothing in my model Serie
class Serie extends Model
{
//
}
Is it normal that the model Serie is empty?
Because, my join works.
What do you think ?
Is there an error?
As Dparoli mentioned in comments if you don't need the below query then your above structure of relationship is normal
Serie::with('cars')->find($id)
But if you want to setup relationship in Serie Model you can do something like below:
class Serie extends Model
{
public function cars() {
return $this->hasMany('App\Car', 'fk_serie'); // your relationship
}
}
And after that you can do:
$series = Serie::with('cars')->find($id); //eager loading cars
$cars = $series->first()->cars;

student and teacher and course relationships in laravel

I have a problem with the relationships in my project in Laravel:
My project consists of:
Student (ID- Name - Mobile - Email)
Teacher (ID - Name - Mobile - Email)
Course (ID - Name - description)
Relationships :
Each course is offered by one or more teachers.
Each teacher offers one or more courses.
Each student enrolled in one or more courses.
Each student attended one or more courses at one teacher
Clarification :
course & teacher = (Many To Many).
course & student = (Many To Many).
student & teacher = (Many To Many).
Through my search I found:
Next two images .. Are these relationships true?
My Work:
- migrations:
Schema::create('courses', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('name');
$table->text('description');
$table->timestamps();
});
Schema::create('students', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('name');
$table->string('mobile');
$table->string('email');
$table->timestamps();
});
Schema::create('teachers', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('name');
$table->string('mobile');
$table->string('email');
$table->timestamps();
});
Schema::create('enrollments', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('course_id')->unsigned();
$table->integer('student_id')->unsigned();
$table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
$table->foreign('student_id')->references('id')->on('students')->onDelete('cascade');
$table->timestamps();
});
Schema::create('teaches', function (Blueprint $table) {
$table->increments('id');
$table->integer('course_id')->unsigned();
$table->integer('teacher_id')->unsigned();
$table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
$table->foreign('teacher_id')->references('id')->on('teachers')->onDelete('cascade');
$table->timestamps();
});
Schema::create('student_course_teacher', function (Blueprint $table) {
$table->increments('id');
$table->integer('enroll_student_id')->unsigned();
$table->integer('enroll_course_id')->unsigned();
$table->integer('teach_teacher_id')->unsigned();
$table->foreign('enroll_student_id')->references('student_id')->on('enrollments')->onDelete('cascade');
$table->foreign('enroll_course_id')->references('course_id')->on('enrollments')->onDelete('cascade');
$table->foreign('teach_teacher_id')->references('teacher_id')->on('teaches')->onDelete('cascade');
$table->timestamps();
});
- models:
- Course:
class Course extends Model
{
protected $table = 'courses';
public function students()
{
return $this->belongsToMany(Student::class, 'enrollments', 'student_id', 'course_id')->withTimestamps();
}
public function teachers()
{
return $this->belongsToMany(Teacher::class, 'teaches', 'teacher_id', 'course_id')->withTimestamps();
}
}
- Student:
class Student extends Model
{
protected $table = 'students';
public function courses()
{
return $this->belongsToMany(Course::class, 'enrollments', 'course_id', 'student_id')->withTimestamps();
}
}
- Teacher:
class Teacher extends Model
{
protected $table = 'teachers';
public function courses()
{
return $this->belongsToMany(Course::class, 'teaches', 'course_id', 'teacher_id')->withTimestamps();
}
}
- Enrollment:
class Enrollment extends Model
{
protected $table = 'enrollments';
}
- Teach:
class Teach extends Model
{
protected $table = 'teaches';
}
Caution: I can not make relationships in (Enrollment & Teach).
My Requests:
Complete relationships
I want to get students for a certain course with teacher information.
I want to take courses with her students and teachers.
I want to get certain teacher courses with students.
Waiting for help,,
This is obviously not tested, but should help you figure out a solution towards your problem.
Name Of Tables
courses (For Course Model)
students (For Student Model)
teachers (For Teacher Model)
course_student (For Many To Many Relation between Student & Course) - For this you will create an extra model (CourseStudent), which will actually be used for Point 6.
course_teacher (For Many To Many Relation between Teacher & Course)
course_student_teacher (For Many To Many Relation between CourseStudent & Teacher)
Models
Course Model
class Course extends Model
{
public function students()
{
return $this->belongsToMany(Student::class)->withTimestamps();
}
public function teachers()
{
return $this->belongsToMany(Teacher::class)->withTimestamps();
}
}
Students Model
class Student extends Model
{
public function courses()
{
return $this->belongsToMany(Course::class)->withTimestamps();
}
}
Teachers Model
class Teacher extends Model
{
public function courses()
{
return $this->belongsToMany(Course::class)->withTimestamps();
}
// Courses/Students Currently Being Taught
public function courseStudents()
{
return $this->belongsToMany(CourseStudent::class, 'course_student_teacher')
->withTimestamps();
}
// List Of Students Currently Taught For Different Courses
public function allStudentsCurrentlyTaught()
{
return $this->courseStudents()->get()->map(function($courseStudent) {
return $courseStudent->student;
})->unique('id');
}
// List Of Courses Currently Taught To Different Students
public function coursesCurrentlyTaughtToStudents()
{
return $this->courseStudents()->get()->map(function($courseStudent) {
return $courseStudent->course;
})->unique('id');
}
// List Of Courses Taught To A Particular Students
public function coursesTaughtToAStudent($studentId)
{
return $this->courseStudents()->get()->where('student_id', $studentId)->map(function($courseStudent) {
return $courseStudent->course;
});
}
// List Of Students Taught For A Particular Course
public function coursesTaughtForACourse($courseId)
{
return $this->courseStudents()->get()->where('course_id', $courseId)->map(function($courseStudent) {
return $courseStudent->course;
});
}
}
CourseStudent Model for creating pivot table course_student_teacher
class CourseStudent extends Model
{
protected $table = 'course_student';
public function course()
{
return $this->belongsTo(Course::class)->withTimestamps();
}
public function student()
{
return $this->belongsTo(Student::class)->withTimestamps();
}
public function teachers()
{
return $this->belongsToMany(Teacher::class, 'course_student_teacher')->withTimestamps();
}
}

Laravel one to many relationship results

Hello i am trying to create one to many relationship. One user from user table could have many companies, on other side company could have only one user.
my migration for company table is
public function up()
{
Schema::create('companies', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('address');
$table->string('city');
$table->string('state');
$table->string('contact_person');
$table->string('phone');
$table->string('industry');
$table->string('website');
$table->integer('id_user')->unsigned();
$table->foreign('id_user')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
}
my user model is
/**
* Get the posts for the user.
*/
public function companies()
{
return $this->hasOne('App\Company','user_id');
}
my company model is
public function users()
{
return $this->belongsTo('App\User','id');
}
i am trying to get all companies for specific user
try with whereHas but no data in relation object
$results = Company::whereHas('users', function ($query) {
$query->where('users.id',1);
})->get();
Where is my error?
First thing you should change is companies() relation. It has to be hasMany, not hasOne:
public function companies()
{
return $this->hasMany('App\Company');
}
Then get user with all his companies:
$result = User::where('id', $id)->with('companies')->first();
Or, if you want to use Company model like in your example and get only companies:
$result = Company::where('user_id', $id)->get();
Also, you're using id_user in migration. Change it to user_id.

Laravel display data from one database table by using the id of that row

So I have a table pages, that looks like this:
public function up()
{
Schema::create('pages', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('name');
$table->integer('category')->unsigned();
] });
Schema::table('pages', function($table) {
$table->foreign('user_id')->references('id')->on('core_users')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('category')->references('id')->on('ecommerce_payment_pages_categories')
->onUpdate('cascade')->onDelete('set null');
});
}
public function down()
{
Schema::drop('pages');
}
And a table categories looking like this:
public function up()
{
Schema::create('ecommerce_payment_pages_categories', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('core_users')
->onUpdate('cascade')->onDelete('cascade');
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::drop('categories');
}
The pages model looks like this:
class Pages extends Model
{
protected $table = 'pages';
public function user() {
return $this->belongsTo("\App\User");
}
protected $fillable = [
];
protected $casts = [
];
public function categories() {
return $this->belongsTo("\App\Models\Categories");
}
}
And the categories model looks like this:
class PaymentPagesCategories extends Model
{
protected $table = 'categories';
public function user() {
return $this->belongsTo("\App\User");
}
protected $fillable = [
];
protected $casts = [
];
public function pages_categories() {
return $this->hasMany("\App\Models\\Pages");
}
}
So in my pages table I save in the column category the id of the category that the user selects from a dynamic select that echoes the category id as value and category names as options. But I cannot save it as simple string because in another menu the user has the option to delete categories, so I want that when a category gets deleted to get deleted from the category column in the page table as well. Right now I display the data from the database like this:
public function getGet()
{
return response()->json(['success' => true, 'payment_pages' => \Auth::user()->payment_pages()->orderBy('id', 'ASC')->get()]);
}
So for the currently authenticated user I display all the data from the page database table.
Right now after the user selects a category from my select I save on the category colum in pages table the ID of the category. I need to make a query in order to display in a different view in html the corresponding to the category id I saved in pages table
Category column in page migration is not set to allow null values.
To allow null values append nullable column modifier to category column.
Rest of the code seems OK.
Page Migration:
public function up()
{
Schema::create('pages', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('name');
$table->integer('category')->unsigned()->nullable(); // <= add this modifier
});
Schema::table('pages', function($table) {
$table->foreign('user_id')->references('id')->on('core_users')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('category')->references('id')->on('ecommerce_payment_pages_categories')
->onUpdate('cascade')->onDelete('set null');
});
}

Categories