Laravel Multiple Table Subquery - laravel

I'm using Laravel 6.0
I have 4 different tables.
Tables:
post_category
id
relation_post_id
post_type
category_id
photo_post
id
title
image
created_at
text_post
id
title
content
created_at
video_post
id
title
video_source_url
created_at
I'd like to list posts in two date ranges from the post_category table. For example
PostCategory::whereBetween('created_at',[$from, $to])->get();
The result should be:
Result
https://i.ibb.co/y53PmJ9/image.png
How can I do that?
Models:
PostCategory
class PostCategory extends Model
{
use SoftDeletes;
protected $table = 'post_category';
public $timestamps = true;
protected $fillable = [
'relation_post_id',
'post_type', // 1: text, 2: photo, 3: video
'category_id',
];
public function text()
{
return $this->belongsTo('App\TextPost','relation_post_id','id');
}
public function photo()
{
return $this->belongsTo('App\PhotoPost','relation_post_id','id');
}
public function video()
{
return $this->belongsTo('App\VideoPost','relation_post_id','id');
}}
TextPost
class TextPost extends Model
{
use SoftDeletes;
protected $table = 'text_post';
public $timestamps = true;
protected $fillable = [
'title',
'content',
];
}
PhotoPost
class PhotoPost extends Model
{
use SoftDeletes;
protected $table = 'photo_post';
public $timestamps = true;
protected $fillable = [
'title',
'image',
];
}
Video Post
class VideoPost extends Model
{
use SoftDeletes;
protected $table = 'video_post';
public $timestamps = true;
protected $fillable = [
'title',
'video_source_url',
];
}

Sure, it's possible. But since we just know your database design but not your codebase, it's hard to say. Intuitively I'd go with a polymorphic relationship.

Related

Trying to get property 'max_rating' of non-object in Laravel

I have these three models in Laravel-5.8
GoalType
class GoalType extends Model
{
protected $table = 'goal_types';
protected $fillable = [
'id',
'name',
];
public function goals()
{
return $this->hasMany('App\Models\Goal');
}
public function ratinglimit()
{
return $this->belongsTo(App\Models\RatingLimit);
}
}
RatingLimit
class RatingLimit extends Model
{
protected $table = 'rating_limits';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'max_rating',
];
public function goaltype()
{
return $this->hasOne('App\Models\GoalType','goal_type_id','id');
}
}
Goal
class Goal extends Model
{
protected $table = 'goals';
protected $fillable = [
'id',
'goal_type_id',
'goal_title',
];
public function goaltype()
{
return $this->belongsTo('App\Models\GoalType','goal_type_id');
}
}
Controller
$goals = Goal::where('is_approved', 3)->get();
A RatingLimit is associated with one GoalType (hasOne) and GoalType has many Goal
When I tried to render max_rating
index.blade
{{$goal->goaltype->ratinglimit->max_rating}}
I got this error:
Trying to get property 'max_rating' of non-object
When I changed it to:
{{ $goal->goaltype->ratinglimit ? $goal->goaltype->ratinglimit->max_rating : '-' }}
it deisplays '-', and the error is no more there. But max_rating in the database is not empty
How do I resolve this?
Thanks
->get() returns a collection! so you should loop it through foreach to have access to each item and then you can use your relation:
#foreach ($goals as $g)
{{$goal->goaltype->ratinglimit->max_rating}}
#endforeach

storing and updating has-many relationships laravel

i m about storing datas using haMany Relatiions
where Cars may have more than picture
and each picture can have only one car
Car Modem Car.php
class Car extends Model
{
protected $table = 'cars';
public $timestamps = true;
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = array('Marque', 'Model', 'sieges', 'climatisation', 'portes', 'transmition', 'price','url','car_id');
public function cars_images()
{
return $this->hasMany(CarsImage::class);
}
CarsImage Model
class CarsImage extends Model
{
protected $table = 'cars_images';
public $timestamps = true;
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = array('url');
public function cars()
{
return $this->belongsTo(Car::class);
}
}
MyController :
public function store(Request $request) {
$car = new Car;
$car->Marque = Input::get('Marque');
$car->Model = Input::get('Model');
$car->sieges = Input::get('sieges');
$car->climatisation = Input::get('climatisation');
$car->portes = Input::get('portes');
$car->transmition = Input::get('transmition');
$car->price = Input::get('price');
$img = new CarsImage;
$img->url = 'jean Luc Picard';
DB::transaction(function() use ($car, $img) {
$car = $car->save();
Car::find($car->id)->cars_images()->save($img);
});
return 'ok';
}
the problem is the car is saved and the url also is saved but with not the car_id
Any help please ?
just use create method:
$car = Car::create([
'Marque' => $request->Marque,
//other fields...
]);
$image = $car->cars_images()->create([
'url' => 'jean Luc Picard'
]);
and don't forget to use $fillable in your models.

RelationNotFoundException in RelationNotFoundException.php

each product hasMany property.
when I use with function:
dd(Product::with(ProductProperty::class)->get());
I got this error :
RelationNotFoundException in RelationNotFoundException.php
Call to undefined relationship [App\Models\ProductProperty] on model [App\Models\Product].
class Product extends Model
{
protected $table = 'products';
protected $fillable = [
'user_id' ,'brand_id' , 'title', 'price', 'current_buy','max_buy','min_buy_per_bill',
'max_buy_per_bill','count','off','seri','short_description','long_description',
];
public function ProductProperty()
{
return $this->hasMany('App\Models\ProductProperty');
}
}
class ProductProperty extends Model
{
protected $table = 'products_properties';
protected $fillable = [
'product_id' ,'parent_id' , 'title','value', 'price', 'current_buy','max_buy','min_buy_per_bill',
'max_buy_per_bill','count','off','seri','short_description','long_description',
];
public function Product()
{
return $this->belongsTo('App\Models\Product');
}
}
Looking at your code you can't use ::class with the with() function. The main reason is the ::class will return the full path with namespace.
Product::with(ProductProperty::class)->get(); is incorrect.
Replace it with Product::with('ProductProperty')->get();

laravel eloquent doesn't use protected table name

In my model i added protected $table, but when i'm going to use it laravel does't use it. This is my role models:
class Role extends Model
{
protected $table = 'role';
protected $primaryKey = 'ROLE_ID';
protected $casts = [
'ACTIVE' => 'boolean',
];
protected $fillable = [
'ROLE', 'ACTIVE', 'TYPE'
];
public $timestamps = false;
public function groups()
{
return $this->belongsToMany(Group::class, GroupRole::class, 'ROLE_ID', 'GROUP_ID');
}
}
And this is Group model:
class Group extends Model
{
protected $table = 'groups';
protected $primaryKey = 'GROUP_ID';
protected $fillable = [
'GROUP_ID', 'GROUP_NAME', 'PARENT_GROUP', 'ACTIVE'
];
protected $casts = [
'ACTIVE' => 'boolean',
];
public $timestamps = false;
public function type()
{
return $this->belongsTo(GroupType::class, 'TYPE', 'TYPE_ID');
}
public function roles()
{
return $this->belongsToMany(Role::class, GroupRole::class, 'GROUP_ID', 'ROLE_ID');
}
}
And this is group_role table model. It handles many to many relation between role and group:
class GroupRole extends Model
{
protected $table = 'group_role';
protected $primaryKey = 'GROUP_ROLE_ID';
protected $fillable = [
'COMMENT', 'ROLE_ID', 'GROUP_ID'
];
public $timestamps = false;
}
Problem begin when i want to use this models. For example:
$role = App\Role::first();
$groups = $role->groups;
Laravel returns this error messages:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'favian_mydb.App\GroupRole' doesn't exist (SQL: select groups.*, App\GroupRole.ROLE_ID as pivot_ROLE_ID, App\GroupRole.GROUP_ID as pivot_GROUP_ID from groups inner join App\GroupRole on groups.GROUP_ID = App\GroupRole.GROUP_ID where App\GroupRole.ROLE_ID = 1)
I tried to replace App\GroupRole with group_role and executing in mysql. It works fine. Am i missing something?
The Problem is in your roles relation:
public function roles()
{
return $this->belongsToMany(Role::class, GroupRole::class,'GROUP_ID','ROLE_ID');
}
The belongsToMany expects the intermediate table name as second argument, not the class name.
So you have to define it like this:
public function roles()
{
return $this->belongsToMany(Role::class, 'group_role','GROUP_ID','ROLE_ID');
}
I think the problem is in you relation functions. Try to use strings instead of Model::class.
Example:
return $this->return $this->belongsTo('App\GroupType', 'TYPE', 'TYPE_ID');
Hope this works.

Using properly of eager loading

I have two tables: contracts and contractitems. I want to display all my Contract items and have a search for searching the contractor name.
Contracts
id
contract_code
contractor_name
ContractItems
id
contracts_id
item_name
class ContractItems extends Eloquent {
protected $table = 'ContractItems';
protected $guarded = [ 'id' ];
public $timestamps = false;
public function contract()
{
return $this->hasOne('Contracts', 'id', 'contracts_id');
}
}
$x = ContractItems::with(array('contract' => function($query){
$query->where('contractor_name', 'LIKE' , '%name%');
}))->take(1)->get();
I tried the code above but it is not displaying the correct data.

Resources