This is my Items model . Now i want to add a new item but i get this error: SQLSTATE[23000]: Integrity constraint violation: 1048
<?php
class Items extends Eloquent
{
protected $guarded = [
'id',
];
protected $fillable = [
'name',
'description',
'price',
'brand',
];
protected $table = 'items';
public function user()
{
return $this->hasOne('User', 'user_ID', 'id');
}
public function size()
{
return DB::table('sizes')->select('size')
->where('id', $this->size_ID)->first()->size;
}
public function color()
{
return DB::table('colors')->select('color')
->where('id', $this->color_ID)->first()->color;
}
public function condition()
{
return DB::table('conditions')->select('type')
->where('id', $this->condition_ID)->first()->type;
}
public function category()
{
return DB::table('categories')->select('category')
->where('id', $this->category_ID)->first()->category;
}
public function images()
{
return DB::table('images')->select('image')
->where('item_id', $this->id)->first()->image;
}
}
And this is my post method to save item.
public function store()
{
$item = new Items;
$item->user_ID = Auth::id();
$item->name = Input::get('name');
$item->description = Input::get('description');
$item->price = Input::get('price');
$item->brand = Input::get('brand');
$item->category = Input::get('Category');
$item->condition = Input::get('Condition');
$item->color = Input::get('Color');
$item->save();
}
Here is a picture of category table , condition and color table has the same logic.
http://imgur.com/9NCMYui
You are creating a relationship between User and Item while not using it.
You can set the populate the relationship manually by filling in the id yourself, but then you don't use the power of the Eloquent ORM.
What I would suggest is getting the current user.
And saving it like this.
$item->user()->save($user);
I suggest for the name of the class Item and not Items.
I find it having much more logic and so do most of the programmers.
The table can still be called items.
Related
So I have this model, say City. And it has a OneToMany relationship with another model, say, Citizen.
On the city model, I have defined a relationship helper function
public function citizens()
{
return $this->hasMany(Citizen::class, 'city_id', 'id');
}
Now my problem is that, in a command, I have :
$cities = City::with('citizens')->get();
foreach ($cities as $city) {
$citizens = $city->citizens->pluck('user');
}
Yet it doesn't return anything. To get values I must turn this line to
$cities = City::all();
foreach ($cities as $city) {
$citizens = $city->citizens()->get()->pluck('user');
}
Does anyone have a clue how this might happen ? This started happening today with no apparent reason.
EDIT
To further illustrate the situation,
$cities = City::with('citizens')->get();
foreach ($cities as $city) {
dd($city->citizens()->count()); // => 5
dd($city->citizens->count()); // => 0
}
Here are the models definitions
// City.php
class City extends Model
{
use Searchable;
protected $table = 'cities';
public $incrementing = false;
protected $perPage = 20;
protected $fillable = [
'name',
'unique_code',
'extra_attributes'
];
protected $casts = [
'id' => 'string',
'codes' => 'array',
'extra_attributes' => SchemalessAttributes::class,
];
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->id = $model->id ?: Str::orderedUuid();
});
}
public function toSearchableArray(): array
{
return [
'name' => $this->name,
];
}
public function citizens()
{
return $this->hasMany(Citizen::class, 'city_id', 'id');
}
}
// Citizen.php
class Citizen extends Model
{
public $incrementing = false;
protected $perPage = 20;
protected $table = "citizens";
protected $fillable = [
'user_id',
'level_id',
'city_id',
];
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->id = $model->id ?: Str::orderedUuid();
});
}
public function user() {
return $this->hasOne(User::class, 'id', 'user_id')->withTrashed();
}
public function city() {
return $this->hasOne(City::class, 'id', 'city_id');
}
}
the relation between City and Citizen is City hasMany Citizens...
In Laravel, hasMany relation reverse is belongsTo Not hasOne, see Laravel doc
so you should correct the relation In Citizen Model like this:
public function city() {
return $this->belongsTo(City::class, 'city_id');
}
There are two issues, one of which OMR has highlighted (you've used an incorrect relationship in your Citizen class), but that isn't the main issue. You're trying to pluck another relationship but unless you explicitly tell it to, Laravel won't eager load that relationship. You've only told it to eager load the Citizen relationship, not the User relationship. Thankfully, Laravel does support nested relationships. You need to update your query thusly:
$cities = City::with('citizens.user')->get();
The best way to solve this issue is by eager loading the citizens when you're getting your cities, that way you wont be executing too many queries (as you will have to get citizens for each city individually), it will save you a lot of execution time in the future when the database gets bigger if you do this :
$cities = City::with('citizens')->get();
foreach($cities as $city) {
$items = $city->citizens->pluck('...');
}
I'm new to laravel Polymorphic Relationship. i have 2 table Supplier and Product and have Category to each table, so i'm decide to use Polymorphic Relationship. i want to query supplier-category but its return empty array.
// My Category Model
class Category extends Model
{
protected $fillable = ['categorizable_type', 'categorizable_id'];
public function categorizable()
{
return $this->morphTo();
}
}
// My Supplier Model
class Supplier extends Model
{
protected $fillable = ['name', 'email', 'phone'];
public function categories()
{
return $this->morphMany(\App\Category::class, 'categorizable');
}
}
// My Product Model
class Product extends Model
{
protected $fillable = ['product_code', 'product_name'];
public function categories()
{
return $this->morphMany(\App\Category::class, 'categorizable');
}
}
// And in SupplierController i want to query categorizable_type
public function index(Request $request)
{
// $product = Category::all();
$product = Category::whereHasMorph('categorizable', Supplier::class , function($query){
$query->where('categorizable_type', 'like', '%foo%');
})->get();
dd($product);
// return response()->json($product);
}
Thanks in advance...
Im make it working by change my code like below
$product = Category::whereHasMorph('categorizable', Supplier::class)->get();
I want to display all liked products of a specific user from the database, but I'm getting an error Integrity constraint violation: 1052 Column 'deleted_at' in where clause is ambiguous .How can I display all liked products of specific user?
Like.php
class Like extends Model
{
use SoftDeletes;
protected $table = 'likeables';
protected $fillable = [
'user_id',
'likeable_id',
'likeable_type',
];
/**
* Get all of the products that are assigned this like.
*/
public function products()
{
return $this->morphedByMany('App\Product', 'likeable');
}
}
Product.php
public function likes()
{
return $this->morphToMany('App\User', 'likeable')->whereDeletedAt(null);
}
public function getIsLikedAttribute()
{
$like = $this->likes()->whereUserId(Auth::id())->first();
return (!is_null($like)) ? true : false;
}
User.php
public function likedProducts()
{
return $this->morphedByMany('App\Product', 'likeable')->whereDeletedAt(null);
}
Blade file
#foreach (Auth::user()->likedProducts as $product)
<h2>{{ $product->price }}</h2>
#endforeach
You have two deleted_at column in users table and products table. That's why the error . change your likedProducts function like this
public function likedProducts()
{
return $this->morphedByMany('App\Product', 'likeable')->whereNull('products.deleted_at');
}
I use PHP, Laravel 5.2 and MySQL.
During user registration, I need to create a new Patient. But, Patient has user id, contact id and guardian id(foreign keys).
When I try to save() the patient, I get the following exception:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'patient_id' in
'field list' (SQL: update users set patient_id = 0, updated_at =
2016-06-07 12:59:35 where id = 6)
The problem is that I DO NOT have patient_id column. Instead I have patientId.
I don't know how to fix this issue. Any help will be appreciated. I can include the migration files if this is important.
UserController.php
public function postSignUp(Request $request)
{
$this->validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:100',
'password' => 'required|min:6'
]);
$guardian = new Guardian();
$guardian->guardianId = Uuid::generate();;
$guardian->save();
$contact = new Contact();
$contact->contactId = Uuid::generate();
$contact->save();
$user = new User();
$user->email = $request['email'];
$user->name = $request['name'];
$user->password = bcrypt($request['password']);
$user->save();
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->user()->save($user);
$patient->contact()->save($contact);
$patient->guardian()->save(guardian);
$patient->save();
Auth::login($user);
// return redirect()->route('dashboard');
}
Patient.php
class Patient extends Model
{
protected $primaryKey='patientId';
public $incrementing = 'false';
public $timestamps = true;
public function user()
{
return $this->hasOne('App\User');
}
public function contact()
{
return $this->hasOne('App\Contact');
}
public function guardian()
{
return $this->hasOne('App\Guardian');
}
public function allergies()
{
return $this->belongsToMany('App\PatientToAllergyAlert');
}
public function medicalAlerts()
{
return $this->belongsToMany('App\PatientToMedicalAlert');
}
}
User.php
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function patient()
{
return $this->belongsTo('App\Patient');
}
}
Contact.php
class Contact extends Model
{
protected $table = 'contacts';
protected $primaryKey = 'contactId';
public $timestamps = true;
public $incrementing = 'false';
public function contact()
{
return $this->belongsTo('App\Patient');
}
}
Guardian.php
class Guardian extends Model
{
protected $table = 'guardians';
protected $primaryKey = 'guardianId';
public $timestamps = true;
public $incrementing = 'false';
public function contact()
{
return $this->belongsTo('App\Patient');
}
}
You have not defined relationships correctly. First of all, fill in table fields into $fillable array in Patient, Contact, Guardian classes (just like in User class).
If you want to use hasOne relationship between Patient and User, you're gonna need user_id field on patients table. You can alternatively use belongsTo relationship.
If you want to use custom column names, just specify them in relationship methods:
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id');
// alternatively
return $this->belongsTo('App\User', 'user_id', 'id');
}
Just go through documentation without skipping paragraphs and you will get going in a few minutes :)
https://laravel.com/docs/5.1/eloquent-relationships#defining-relationships
Also, this will not work:
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->user()->save($user);
new Patient() only creates the object, but does not store it in DB, so you will not be able to save relationships. You need to create the object and store it to DB to avoid this problem:
$patient = Patient::create(['patientId' => (string)Uuid::generate()]);
$patient->user()->save($user);
...
// or
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->save();
$patient->user()->save($user);
...
When you're setting up your relationship, you can to specify the name of the primary key in the other model. Look here.
I'm not sure, but I think you relationships are not defined properly.
I have the following Ticket Table
if(!Schema::hasTable('tblticket')) {
Schema::create('tblticket', function (Blueprint $table) {
$table->increments('TicketID');
$table->string('Subject', 50);
$table->integer('ParentTicketID')->nullable()->unsigned();
$table->timestamps();
$table->foreign('ParentTicketID')->references('TicketID')->on('tblticket');
});
}
Primary Key is TicketID and There is another column called ParentTicketID, which is related to TicketID.
Below is Ticket Model
class TicketModel extends Model
{
public $table = 'tblticket';
public $primaryKey = 'TicketID';
public $timestamps = true;
public function TicketReplies() {
return $this->belongsTo('\App\Models\TicketModel', 'TicketID');
}
}
Below is my Query
$Ticket = \App\Models\TicketModel
::with('TicketReplies')
->where('ParentTicketID', '=', $TicketID)
->first();
I am trying to get all child tickets of a Ticket. but I am getting null.
Can you please guide if I am missing something.
this is my sample code, you can try this, I hope that will help you
/*---------------------------------------------------------
* Relationship with same table, means recursive key
* --------------------------------------------------------
*/
//this will get the childern against parent.
public function doseage_childs(){
return $this->hasMany('App\Models\DoseageForm', 'parent_id', 'id');
}
//this will get the parent against childern
public function doseage_parent(){
return $this->belongsTo('App\Models\DoseageForm', 'parent_id', 'id');
}
Edited
update your this method
public function TicketReplies() {
return $this->belongsTo('\App\Models\TicketModel', 'TicketID');
}
like this
public function TicketReplies() {
return $this->hasMany('\App\Models\TicketModel','ParentTicketID' ,'TicketID');
}
and update your query model like this, because you already getting TicketReplies relationships.
$Ticket = \App\Models\TicketModel
::with('TicketReplies')
->where('TicketID', '=', $TicketID)
->first();
You relationship will works then