OrderProducts Eloquent:
class OrderProduct extends Model
{
use HasFactory;
protected $table = 'order_products';
}
I create a model for my table name called order_products.
My Eloquent name is OrderProduct. Then I change the table name in Eloquent to protected $table = "order_products"`.
Still, I'm getting order_product table doesn't exist issue?
Why?
Changing the Model would not automatically change the table name within your DB
You can specify a custom table name by defining a table property on your model:
class OrderProduct extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'order_products';
}
Ref: https://laravel.com/docs/8.x/eloquent#table-names
Related
The problem is that the query can't find the specific_method(specific_method, specific_model,SpecificModel,specificMethod etc...), that should been joined with the method WITH from Laravel Eloquent. Any ideas how to solve it?
My code:
//SpecificModel
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SpecificModel extends Model {
protected $guard_name = 'web';
protected $table = 'SpecificTable';
protected $guarded = ['id'];
public function specificMethod(){
return $this->belongsTo('App\Models\AnotherModel','AnotherModel_id');
}
}
//AnotherModel
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AnotherModel extends Model {
protected $guard_name = 'web';
protected $table = 'AnotherTable';
protected $guarded = ['id'];
}
//Query method
$model = app('App\Models\SpecificModel');
$query = $model::with('specificMethod:id,title');
$query = $query->orderBy('specific_method.title','desc');
return $query->get();
//Error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'"specific_method.title"' in 'order clause' (SQL: select * from
`SpecificModel` where `SpecificModel`.`deleted_at` is null order by
`specific_method`.`title` desc)
This happens because the belongsTo relationship does not execute a join query as you expect it to (as you can see from the error you get). It executes another query to get the related model(s). As such you will not be able to order the original model by related models columns.
Basically, 2 queries happen:
Fetch the original model with SELECT * from originalModel ...*
Fetch the related models with SELECT * from relatedModel where in id (originalModelForeignKeys)
Then Laravel does some magic and attaches the models from the 2nd query to the correct models from the first query.
You will need to perform an actual join to be able to order the way you want it to.
Is there any way to soft delete all the existing rows in a table?
I have tried ( Prospect::delete(); ) it deleted all the rows permanently, But it doesn't work in soft deleting.
If you are using Laravel framework older than 4.2, then you can set the soft delete in your model as,
class ModelName extends Eloquent {
protected $table = 'table_name';
protected $softDelete = true;
}
If you are using Laravel framework 4.2, then you can set the soft delete in your model as,
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class ModelName extends Eloquent {
use SoftDeletingTrait;
protected $table = 'table_name';
}
If you are using Laravel framework above 4.2, then you can set the soft delete in your model as,
use Illuminate\Database\Eloquent\SoftDeletes;
class ModelName extends Eloquent {
use SoftDeletes;
protected $table = 'table_name';
}
I hope you are using Laravel 5. So you can use the third method.
look at this soft delete
use this trait in your model :
use Illuminate\Database\Eloquent\SoftDeletes;
and add this to your model and database schema :
model:
class Flight extends Model
{
use SoftDeletes;
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = ['deleted_at'];
}
database schema
Schema::table('flights', function ($table) {
$table->softDeletes();
});
Now, when you call the delete method on the model, the deleted_at column will be set to the current date and time. And, when querying a model that uses soft deletes, the soft deleted models will automatically be excluded from all query results.
To determine if a given model instance has been soft deleted, use the trashed method:
if ($flight->trashed()) {
//
}
It usually not delete rows in database.You should add a column isActive etc. and set it (1/0) or (true/false).
if you want show rows,you should "Select * from table Where isActive=1"
MySQL Tables:
- category
- unit
- category_unit (many to many)
- category_id
- unit_id
Laravel 5 Models:
<?php
class Unit extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'unit';
}
class Category extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'category';
public function units()
{
return $this->morphToMany('App\Unit', 'category_unit'); // Table not in plural.
}
}
Controller Code:
$category = Category::find($id);
var_dump($category->units);
Error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'database.category_units' doesn't exist (SQL: select `unit`.*, `category_units`.`category_unit_id` as `pivot_category_unit_id`, `category_units`.`unit_id` as `pivot_unit_id` from `unit` inner join `category_units` on `unit`.`id` = `category_units`.`unit_id` where `category_units`.`category_unit_id` = 1 and `category_units`.`category_unit_type` = App\Category)
Laravel 5 is trying to find the table category_unit as the plural category_units. As my database is not new and I already used it in production servers, I cannot change the table name.
How can I do to Laravel 5 use it with singular name?
The problem here is that you are trying to create Many to Many relationship using a polymorphic one.
The morphToMany() method doesn't take the table name as the second argument. I think your case is simpler, just change the relation to belongsToMany()
So your code should be
class Category extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'category';
public function units()
{
return $this->belongsToMany('App\Unit', 'category_unit'); // Table not in plural.
}
}
I have 3 tables: vehicles, drivers and vehicle_driver_owners.
drivers table includes all the registered drivers. vehicles table includes all the registered vehicles. vehicle_driver_owners is a pivot table. It shows which drivers act as owners to a particular vehicle. (A vehicle can have multiple owners and vice-versa)
I have made relation in all the 3 models(Vehicle, Driver and VehicleDriverOwner)
Here's the Vehicle model
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Vehicle extends Eloquent {
use SoftDeletingTrait;
protected $table = 'vehicles';
protected $softDelete = true;
// EACH VEHICLE CAN BELONG TO MANY OWNERS
public function owners(){
return $this->belongsToMany('Driver', 'vehicle_driver_owners', 'vehicle_driver_owners_vehicle_id', 'vehicle_driver_owners_driver_id');
}
}
Here's the Driver model
class Driver extends Eloquent{
protected $table = 'drivers'
//EACH DRIVER CAN BE OWNER OF MANY VEHICLES
public function vehicleOwner(){
return $this->belongsToMany('Vehicle', 'vehicle_driver_owners', 'vehicle_driver_owners_driver_id', 'vehicle_driver_owners_vehicle_id');
}
}
Here's the VehicleDriverOwner model
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class VehicleDriverOwner extends Eloquent {
use SoftDeletingTrait;
protected $table = 'vehicle_driver_owners';
protected $fillable = ['vehicle_driver_owners_vehicle_id', 'vehicle_driver_owners_driver_id'];
protected $softDelete = true;
}
i was trying to use the softDelete feature of laravel. A vehicle has 3 owners and i want to delete one of them. i also want to keep that entry in database. So i used softDelete feature. After deleting that particular owner, deleted_at column of that row in vehicle_driver_owners table was filled with the date.
But now i'm trying to view the owners of vehicle by using Vehicle::find(5)->owners. It shows that deleted owner as well
Add whereNull('vehicle_driver_owners.deleted_at') to the function owners in Vehicle
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Vehicle extends Eloquent {
use SoftDeletingTrait;
protected $table = 'vehicles';
protected $softDelete = true;
// EACH VEHICLE CAN BELONG TO MANY OWNERS
public function owners(){
return $this->belongsToMany('Driver', 'vehicle_driver_owners', 'vehicle_driver_owners_vehicle_id', 'vehicle_driver_owners_driver_id')
->whereNull('vehicle_driver_owners.deleted_at');
}
}
I've got the following tables:
products (
id
)
attributes (
id
name
value
)
products_attributes (
product_id,
attribute_id
)
And I need to be able to query for all of the attributes of a specific product. I tried doing this with the FLUENT QUERY BUILDER but I'm getting lost in my own code.
Can someone help me out with an example?
Usually you would create models for both of your entities, in which you can specify the relationships:
class Product extends Eloquent
{
protected $table = 'products';
public function attributes()
{
return $this->belongsToMany('Attribute', 'products_attributes');
}
}
class Attribute extends Eloquent
{
protected $table = 'attributes';
public function products()
{
return $this->belongsToMany('Product', 'products_attributes');
}
}
The belongsToMany() method sets up a many-to-many relationship. The first parameter specifies the related model class name, the second one the name of the database table that holds the connections between the two entities.
To find a product with ID 1234, you would fetch it like this:
$product = Product::find(1234);
You can then magically access all of its attributes like this:
$attributes = $product->attributes;
For more information, you can refer to the documentation.