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');
}
}
Related
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
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"
I've two tables jobs table (id,title,description)->Jobs model
and candinates table (id,applied_job_id(FK jobs),user_id)->Candidate model
I want to get all the rows of jobs with the total number of candidate applied for each job
Jobs model
class Jobs extends Model
{
public function appliedCount()
{
return $this->hasMany('App\Models\Candidate','applied_job_id');
}
}
Candidate Model
class Candidate extends Model
{
protected $table = 'candidate';
}
Here is my query
$query = Jobs::limit($this->limit)->offset($offset)->get();
Currently it returns all the rows of jobs table
Note:
I will fetch the result as JSON
You're defining the relationship with a non existent model Candidate, where as the model is named JobActivity which uses the table candidate, when the table is actually named candidates. Try this.
class Jobs extends Model
{
public function candidate()
{
return $this->hasMany(Candidate::class,'applied_job_id');
}
}
class Candidate extends Model
{
}
$jobs = Jobs::withCount('candidate')->limit($this->limit)->offset($offset)->get();
I have two models User and UserType declared as follows:
class User extends Model {
protected $table = 'user';
protected $primaryKey = 'user_id';
public function company() {
return $this->hasOne('App\Models\Company', 'company_id', 'company_id');
}
public function userType() {
return $this->hasOne('App\Models\UserType', 'user_type_id', 'user_type_id');
}
}
class UserType extends Model {
protected $table = 'user_type';
protected $primaryKey = 'user_type_id';
}
Now, I query the relationships using:
User::with('userType', 'company')->all()
Strangely, I get the company but userType is always null.
The MySQL query log shows that Laravel was able to get the user_type record.
The only difference between company and userType relationships are the data type of the primary keys. company.company_id is numeric while user_type.user_type_id is a string.
I think it is related to the data type of the keys however, I have a similar setup on Laravel 5.1 and it runs perfectly.
Laravel supports non-numeric primary keys but you need to set:
public $incrementing = false;
on your model class.
I corrected the issue by changing UserType definition to:
class UserType extends Model {
protected $table = 'user_type';
protected $primaryKey = 'user_type_id';
public $incrementing = false;
}
The first issue i notice with your relationship is that the first user_type_id you have passed to the hasOne function is wrong because you have the user_type_id as the primary key of the user_type table. The second argument of the hasone must be the foreign key of the parent table which is the user. So if you have anything like user_id in the user_type table use that instead.
But if thats not the case and user rather belongs to UserType then you have to change the hasOne to belongsTo.
I am just starting with ORM. I had a question, this is my tabel --
table a - (aid, aname, atag);
table b - (bid, aid, bname, .. );
It is One to Many relationship - that is One aid can belong to many bid but one bid can belong to only one aid.
So I was trying out this code, In the out put I want -- (bname,aname) for all the records.
A model --
class A extends Eloquent {
protected $table = 'a';
protected $primaryKey = 'aid';
public function brelation() {
$this->belongsToMany('B','aid');
}
}
B model --
class B extends Eloquent {
protected $table = 'b';
protected $primaryKey = 'bid';
public function getANames() {
$this->hasOne('A','aid');
}
}
In Controller --
foreach(B::with('getANames')->get() as $b_item){
echo $b_item->bname." , ".$b_item->aname;
}
Couple of points to clarify --
1) I have to specify the foreign key to make sure they map. Because in my actual case they are named differently.
2) I am using Laravel 4.
Can someone show me what I did wrong and how I can get the desired result.
===== Update =====
class A extends Eloquent {
protected $table = 'a';
protected $primaryKey = 'aid';
public function brelation() {
$this->belongsTo('B','aid');
}
}
I still cannot access the aname column i.e ($b_item->aname) in the controller.
A couple of things you should be aware of:
If you have a custom primary key, you need to set the $primaryKey property on your eloquent models to the primary keys you have in the DB.
You can't mix and match belongsToMany relationships with anything other than belongsToManys. A belongsToMany is exclusively for the case where you have two tables that are connected by a pivot table. In your case, B belongsTo A, and A hasMany B.