I have two models: Dish and DishCategory. I decided to implement a "One to many" relationship.
Here's a migration for Dish model:
Schema::create('dishes', function (Blueprint $table) {
$table->increments('id');
$table->string('dish', 50);
$table->string('photo');
$table->double('price', 8, 2);
$table->integer('category_id');
$table->integer('type_id'); /* 1 - menu for delivery; 0 - general menu */
});
And a migration for DishCategory model:
Schema::create('dish_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('category');
});
I've created a method called dish() in DishCategory model:
public function dish()
{
return $this->hasMany('App\Dish');
}
And dish_category() in Dish model:3
public function dish_category()
{
return $this->belongsTo('App\DishCategory', 'category_id');
}
I'm trying to set up a foreign key in my relationship, so it's been set up in dish_category() method as a second parameter of belongsTo(). But it doesn't work. What is the workaround?
Change the dish() relationship definition to:
public function dish()
{
return $this->hasMany('App\Dish', 'category_id');
}
And dish_category() is defined correctly.
If you also want to add a constraint, add this to the dishes table migration:
Schema::table('dishes', function (Blueprint $table) {
$table->foreign('category_id')->references('id')->on('dish_categories');
});
Related
I have a customer model that has many contacts. I defined a relationship to get the most recent contact of the customer using the "Has One Of Many" relationship in Laravel 8:
Models
class Customer extends Model
{
use HasFactory;
public function contacts()
{
return $this->hasMany(Contact::class);
}
public function latestContact()
{
return $this->hasOne(Contact::class)->ofMany('contacted_at', 'max')->withDefault();
}
}
class Contact extends Model
{
use HasFactory;
protected $casts = [
'contacted_at' => 'datetime',
];
public function customer()
{
return $this->belongsTo(Customer::class);
}
}
Migration (contact model)
class CreateContactsTable extends Migration
{
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->softDeletes();
$table->foreignID('customer_id');
$table->string('type');
$table->dateTime('contacted_at');
});
}
}
In my view, I want to show all customers and order them by their latest contact. However, I can't figure out how to do that.
I tried to achieve it via the join method but then I obviously get various entries per customer.
$query = Customer::select('customers.*', 'contacts.contacted_at as contacted_at')
->join('contacts', 'customers.id', '=', 'contacts.customer_id')
->orderby('contacts.contacted_at')
->with('latestContact')
Knowing Laravel there must be a nice way or helper to achieve this. Any ideas?
I think the cleanest way to do this is by using a subquery join:
$latestContacts = Contact::select('customer_id',DB::raw('max(contacted_at) as latest_contact'))->groupBy('customer_id');
$query = Customer::select('customers.*', 'latest_contacts.latest_contact')
->joinSub($latestContacts, 'latest_contacts', function ($join){
$join->on([['customer.id', 'latest_contacts.customer_id']]);
})
->orderBy('latest_contacts.latest_contact')
->get();
More info: https://laravel.com/docs/8.x/queries#subquery-joins
I suspect there is an issue with your migration, the foreign key constraint is defined like this:
Check the documentation:
https://laravel.com/docs/8.x/migrations#foreign-key-constraints
Method 1: define foreign key constraint
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->foreignId('consumer_id')->constrained();
$table->string('type');
$table->dateTime('contacted_at');
$table->timestamps();
$table->softDeletes();
});
}
Method 2: define foreign key constraint
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('customer_id');
$table->foreign('customer_id')->references('id')->on('customers');
$table->string('type');
$table->dateTime('contacted_at');
$table->timestamps();
$table->softDeletes();
});
}
Hello everyone I'm currently working on a laravel project where I have a parent table that has the id's of three tables referenced to it. These table migrations also have their models respectively. Here are the table migrations files respectively:
create_products_table.php
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_id', 10);
$table->string('product_name');
$table->string('image');
$table->string('images');
$table->string('product_description');
$table->bigInteger('size_id')->unsigned();
$table->string('color');
$table->string('product_quantity');
$table->string('old_price');
$table->string('discount');
$table->string('product_price');
$table->bigInteger('user_id')->unsigned()->nullable();
$table->bigInteger('category_id')->unsigned();
$table->bigInteger('gender_id')->unsigned();
$table->timestamps();
$table->foreign('size_id')->references('id')->on('sizes')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->foreign('gender_id')->references('id')->on('genders')->onDelete('cascade');
});
create_genders_table.php
Schema::create('genders', function (Blueprint $table) {
$table->id();
$table->string('gender_class');
$table->timestamps();
});
create_categories_table.php
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('cat_name');
$table->timestamps();
});
create_sizes_table.php
Schema::create('sizes', function (Blueprint $table) {
$table->id();
$table->string('sizes');
$table->timestamps();
});
Also this is how I defined the relationships on their models respectively
Product.php
public function category()
{
return $this->belongsTo(Category::class);
}
public function gender()
{
return $this->belongsTo(Gender::class);
}
public function size()
{
return $this->belongsTo(Size::class);
}
Category.php
public function products()
{
return $this->hasMany(Product::class);
}
Gender.php
public function products()
{
return $this->hasMany(Product::class);
}
Size.php
public function products()
{
return $this->hasMany(Product::class);
}
I'm actually a laravel beginner and I studied eloquent model relationships at laravel.com so what I did was just based on my understanding of one to many relationships. When I check all my request with dd($request), category_id, gender_id, size_id all show null and I believe it's because I didn't define the relationship properly. Now this is where I seriously need your assistance.
So please my experienced developers I seriously need your help I'll really be grateful if I get your replies today. Thanks in advance.
=>Everything is right, just make changes in the products migration add this code.
$table->foreign('size_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('gender_id')->references('id')->on('products')->onDelete('cascade');
=>and migrate table
I know this question has been asked a lot but all answers didn't seem to work for me - or at least the questions I found were about the pivot table.
I have a many to many relationship (User - Appointment) which is joined by the pivot table "apointment_user", see migrations below.
Schema::create('appointment_user', function (Blueprint $table) {
$table->unsignedInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedInteger('appointment_id')->nullable();
$table->foreign('appointment_id')->references('id')->on('appointments');
$table->primary(['user_id','appointment_id']);
$table->timestamps();
});
Schema::create('appointments', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->dateTime('date');
$table->string('location');
$table->dateTime('departure');
$table->timestamps();
});
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->date('last_login')->nullable();
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
class User extends Model {
protected $with = ['appointments'];
public function appointments() : BelongsToMany {
return $this->belongsToMany(Appointment::class);
}
}
class Appointment extends Model {
public function users() : BelongsToMany {
return $this->belongsToMany(User::class);
}
}
I have a user with the ID 1 and about 10 appointments, which I do attach to the relationship in a seeder. The pivot table has 10 records, as intended (User ID is always 1).
However, if I dump my User object using dd(User::find(1)), the relationship is always an empty collection. However, a 1:n relationship (between a role works well).
Does anybody see what I'm missing? Any help is appreciated.
Many thanks and kind regards
Edit
I just tried some other kind of dumping. I've simply returned my User-Object as JSON-response and there the relationship is filled with 10 appointments... strange.
Though it seems that your table and column names are as Laravel would guess, have you tried expliciting the names?
class User extends Model {
protected $with = ['appointments'];
public function appointments() : BelongsToMany {
return $this->belongsToMany(Appointment::class, 'appointment_user', 'user_id', 'appointment_id');
}
}
class Appointment extends Model {
public function users() : BelongsToMany {
return $this->belongsToMany(User::class, 'appointment_user', 'appointment_id', 'user_id');
}
}
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;
I need to implement model for table with only two foreign keys. In my db I have tables like this:
product (id_product, ...)
category_to_product (FK id_category, FK id_product)
category (id_category, ...)
How to manage this connections in Laravel? Should I implement model for merge table and how it may looks? category_to_product table does not represent entity(/model) and have only design-relation property.
Database Migrations
CategoryToProduct
Schema::create('category_to_product', function(Blueprint $table)
{
$table->integer('id_category')->unsigned();
$table->foreign('id_category')
->references('id_category')
->on('categories')
->onDelete('cascade');
$table->integer('id_product')->unsigned();
$table->foreign('id_product')
->references('id_product')
->on('products')
->onDelete('cascade');
});
Products
Schema::create('products', function(Blueprint $table)
{
$table->increments('id_product');
// ...
});
Categories
Schema::create('categories', function(Blueprint $table)
{
$table->increments('id_category');
// ...
});
#pc-shooter is right about creating methods.
But you still have to create the pivot table with your migration first
Schema::create('products', function(Blueprint $table)
{
$table->increments('id')
$table->string('name');
}
Schema::create('categories', function(Blueprint $table)
{
$table->increments('id')
$table->string('name');
}
Then your pivot table
Schema::create('category_product', function(Blueprint $table)
{
$table->integer('category_id')
$table->foreign('category_id')->references('id')->on('categories');
$table->integer('product_id');
$table->foreign('product_id')->references('id')->on('products');
// And finally, the indexes (Better perfs when fetching data on that pivot table)
$table->index(['category_id', 'product_id'])->unique(); // This index has to be unique
}
Do the following:
In the model Category:
public function products(){
return $this->belongsToMany('Category');
}
In the model Product:
public function categories(){
return $this->belongsToMany('Category', 'category_to_product');
}
In the model CategoryToProduct:
public function categories() {
return $this->belongsTo('Category');
}
public function products() {
return $this->belongsTo('Product');
}
Note the naming of these methods!
Those are the same as the DB-table names. See ChainList's
answer.