morphToMany column not found - laravel

I follow tutorial from laravel documentation but it seems the tutorial not complete to explain argument morphToMany to explicit determine what the function should point to.
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'tagables.tagables_id' in 'field list' (SQL: select tags.*,
tagables.tagables_id as pivot_tagables_id,
tagables.tag_tag_id as pivot_tag_tag_id,
tagables.tagables_type as pivot_tagables_type from tags inner
join tagables on tags.tag_id = tagables.tag_tag_id where
tagables.tagables_id = 1 and tagables.tagables_type =
App\Models\Comic)
media table
Schema::create('media', function (Blueprint $table) {
$table->mediumIncrements('media_id)->nullable(false);
$table->string('title', 255);
});
tags table // one row inside tag ( walking )
Schema::create('tags', function (Blueprint $table) {
$table->mediumIncrements('tag_id');
$table->string('tag_name', 255);
});
tagables table
Schema::create('tagables', function (Blueprint $table) {
$table->unsignedMediumInteger('tag_id')->nullable(false);
$table->unsignedMediumInteger('tagable_id')->nullable(false);
$table->string('tagable_type', 255)->nullable(false);
});
comic model
public function tags()
{
return $this->morphToMany(Tag::class, 'tagable');
}
comic controller
// insert new comic
$comic = Comic::create([
'title' => 'Doraemon',
]);
// Insert into tagables table with current comic id and bind to tag id 1
which is walking
$comic->tags->create([
'tag_id' => 1
]);
it succes to insert into media but failed to insert into tagables table.

I found some mistakes in your code. Please try to rewrite this code. There is a working example of your code. I have checked it for you
2021_04_10_073813_create_media_table.php
Schema::create('media', function (Blueprint $table) {
$table->id();
$table->string('name', 255);
$table->timestamps();
});
2021_04_10_073837_create_tags_table.php
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name', 255);
$table->timestamps();
});
2021_04_10_073856_create_taggables_table.php
Schema::create('taggables', function (Blueprint $table) {
$table->id();
$table->unsignedMediumInteger('tag_id')->nullable(false);
$table->unsignedMediumInteger('taggable_id')->nullable(false);
$table->string('taggable_type');
$table->timestamps();
});
class Media extends Model
{
protected $guarded = [];
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
}
class Tag extends Model
{
protected $guarded = [];
public function medias()
{
return $this->morphedByMany(Media::class, 'taggable');
}
}
And finally in a some Controller
$media = Media::create([
'name' => 'media name1',
]);
$tag = $media->tags()->create([
'name' => 'tag name1',
]);

Related

Laravel save HasMany realtion

I have a set that has a list of group and each group has a list of attributes like this
//sets
Schema::create('sets', function (Blueprint $table) {
$table->id();
$table->string('name');
});
//groups
Schema::create('groups', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignId('set_id')->constrained('sets')->onDelete('cascade');
});
//attributes
Schema::create('attributes', function (Blueprint $table) {
$table->id();
$table->string('name');
});
//set_group_attributes
Schema::create('set_group_attributes', function (Blueprint $table) {
$table->foreignId('set_id')->constrained('sets')->onDelete('cascade');
$table->foreignId('group_id')->constrained('groups')->onDelete('cascade');
$table->foreignId('attribute_id')->constrained('attributes')->onDelete('cascade');
$table->integer('position');
$table->unique(['set_id', 'attribute_id']);
});
I need to save the set with groups and attributes, this is my code :
$set = Set::create(['name' => $request->name]); ---> save the set
$set->groups()->createMany($request->groups); ---> save the group
//set model
public function groups(): HasMany
{
return $this->hasMany(Group::class, 'set_id','id');
}
My question is how to save the attributes with laravel eloquent?
Here we can use attach like in Docs with belongsToMany
//group model
/**
* #return BelongsToMany
*/
public function attributes(): BelongsToMany
{
return $this->belongsToMany(Attribute::class, 'set_group_attributes', 'group_id', 'attribute_id')->withPivot('position');
}
// save attributes of groups
foreach ($attributes as $attribute) {
$group->attributes()->attach($attribute['id'], ['set_id' => $model->id, 'position' => $attribute['position']]);
}

get all tags from several posts at the same time

I need to create a query that get all tags from an array of posts.in a many-to-many polymorphic relationship between tags and posts
TAG MODEL
class Tag extends Model
{
use HasFactory;
protected $guarded = ['id'];
//
public function posts()
{
return $this->morphedByMany(Post::class, 'taggable');
}
}
POST MODEL
class Post extends Model
{
use HasFactory;
protected $guarded = ['id'];
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
}
TAG MIGRATION
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
TAGGABLE MIGRATION
public function up()
{
Schema::create('taggables', function (Blueprint $table) {
$table->id();
$table->bigInteger('tag_id')->unsigned();
$table->morphs('taggable');
$table->foreign('tag_id')->references('id')->on('tags')
->onDelete('cascade')
->onUpdate('cascade');
});
}
POST MIGRATION
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description');
// 1 borrador, 2 revision, 3 publicado, 4 caducado
$table->enum('status', [Post::BORRADOR, Post::REVISION, Post::PUBLICADO, Post::CADUCADO]);
// Para diferenciar entre publicaciones del Sistema (Admin = 1) o de usuarios normales (USERS = 2)
$table->enum('type', [Post::ADMIN, Post::USERS]);
$table->boolean('atemporal');
$table->string('slug')->unique();
$table->unsignedBigInteger('user_id')->nullable();
$table->unsignedBigInteger('survey_id')->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('set null');
$table->foreign('survey_id')->references('id')->on('surveys');
$table->timestamps();
});
CATEGORIES MIGRATION
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->unsignedBigInteger('parent_id')->nullable();
$table->string('slug');
$table->foreign('parent_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
PIVOT TABLE CATEGORY_POST
Schema::create('category_post', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('post_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->timestamps();
});
RELATIONSHIP POST
public function categories()
{
return $this->belongsToMany(Category::class);
}
RELATIONSHIP CATEGORY
public function posts()
{
return $this->belongsToMany(Post::class);
}
I have tried this but I can't get it to work
$posts = Post::whereHas('categories', function($query) {
$query->whereIn('category_id', [$this->categoriaTags]);
})->get();
// Here I get the list of posts from which I want to get their tags, this is OK.
//But then I can't get the right query to get the tags.
$tags = Tag::whereHasMorph('posts', function($query) use($posts){
$query->where('tag_id', $posts);
})->get();
Any suggestions? Thank you
You are close, but you are querying the wrong column, and using the wrong builder method. You want:
$tags = Tag::whereHasMorph('posts', function ($query) use ($posts) {
$query->whereIn('id', $posts->pluck('id'));
})->get();

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'blogpost_post_id' in 'field list'

I'm stumped with the use of Pivot Table on Laravel. I've read several similar posts with no success.
I'm a complete beginner. Here's the message I have.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'blogpost_post_id' in 'field list' (SQL: insert into blogpost_blogtag (blogpost_post_id, blogtag_tag_id) values (1, 2))
The issue is pretty simple. Laravel is adding the name of the table before the name of the column, and I can't find out why.
Laravel calls blogpost_post_id whereas the name of the column is simply post_id
Laravel calls blogtag_tag_id whereas the name of the column is simply tag_id
The models
Blogpost.php
public function blogtags(){
return $this->belongsToMany('App\Blogtag');
}
Blogtag.php
public function blogposts(){
return $this->belongsToMany('App\Blogpost');
}
I've also declared in the **Postcategory.php** model the following
public function blogposts()
{
return $this->hasmany('App\Blogpost');
}
The tables:
blogpost table
public function up()
{
Schema::create('blogposts', function (Blueprint $table) {
$table->increments('post_id');
$table->integer('post_editorid')->default(0);
$table->string('post_title');
$table->string('post_slug');
$table->text('post_content');
$table->integer('post_categoryid');
$table->boolean('post_banned')->default(0);
$table->integer('post_moderatorid')->default(0);
$table->dateTime('post_bandate')->nullable($value = true);
$table->string('post_picture')->nullable($value = true);
$table->string('post_extlink')->nullable($value = true);
$table->softDeletes();
$table->timestamps();
});
}
Postcategories table
public function up()
{
Schema::create('postcategories', function (Blueprint $table) {
$table->increments('cat_id');
$table->string('cat_name')->unique();
$table->timestamps();
});
}
Blogtags table
public function up()
{
Schema::create('blogtags', function (Blueprint $table) {
$table->increments('tag_id');
$table->string('tag_kw')->unique();
$table->timestamps();
});
}
And the PIVOT table
public function up()
{
Schema::create('blogpost_blogtag', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id');
$table->integer('tag_id');
$table->timestamps();
});
}
And the controller (store)
public function store(Request $request)
{
//dd($request->all());
$this->validate($request, [
'posttitle' => 'required|min:4|max:255|string',
'postcontent' => 'required|min:30|max:3000|string',
'postpict' => 'nullable|image',
'post_categoryid' => 'required',
'postlink' => 'nullable|max:255|string',
'blogtags' => 'nullable',
]);
if ($request->hasFile('postpict')) {
$postpict = $request->postpict;
$postpict_new_name = time().$postpict->getClientOriginalName();
$postpict->move('uploads/postpicts/', $postpict_new_name);
$picturl = 'uploads/postpicts/' . $postpict_new_name;
}else{
$picturl = NULL;
}
$blogpost = Blogpost::create([
'post_title' => $request->posttitle,
'post_content' => $request->postcontent,
'post_categoryid' => $request->post_categoryid,
'post_picture' => $picturl,
'post_extlink' => $request->postlink,
'post_slug' => str_slug($request->posttitle)
]);
$blogpost->blogtags()->attach($request->blogtags);
$messageposttitle = $request->posttitle;
$message = $messageposttitle . ' is successfully stored';
$title = '';
Toastr::success($message, $title, ["positionClass" => "toast-top-center"]);
return redirect()->back();
}
$blogpost->blogtags()->attach($request->blogtags);
I'll be happy to learn about the mistake I've done.
Try to use custom foreign-key
Blogpost.php
public function blogtags(){
return $this->belongsToMany('App\Blogtag','blogpost_blogtag','post_id','tag_id');
}
Blogtag.php
public function blogposts(){
return $this->belongsToMany('App\Blogpost','blogpost_blogtag','tag_id','post_id');
}

SQLSTATE[42S22]: Column not found:

I am getting this error unknown column city = Faislabad but i have this column in my database. I want to fetch the data in which city is faislabad.
Code of my controller is
public function chart(Request $request)
{
$users = Disease::where("city=$request->city")
->get();
$chart = Charts::database($users, 'bar', 'highcharts')
->title("Monthly new Register Users")
->elementLabel("Total Users")
->dimensions(1000, 500)
->responsive(false)
->groupBy('name');
return view('test1',compact('chart'));
}
And the migration for my table is
public function up()
{
Schema::create('diseases', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('city');
$table->string('symptomps');
});
}
Please tell me what I am doing wrong in this.
Change:
$users = Disease::where("city=$request->city")->get();
to
$users = Disease::where('city', $request->city)->get();

Laravel 4 How to Filter a Polymorphic Table

I have a polymorphic table called 'Item':
Schema::create('items', function(Blueprint $table) {
$table->increments('id');
$table->text('itemable_type')->nullable();
$table->string('itemable_id')->nullable();
$table->integer('subject_id')->nullable();
$table->integer('user_id')->nullable();
$table->integer('new')->nullable();
$table->integer('school')->nullable();
$table->string('private')->nullable();
$table->text('snippet')->nullable();
$table->string('elementSubject')->nullable();
$table->integer('follow_id')->nullable();
$table->timestamps();
});
Also have a table called 'Follow':
Schema::create('follows', function(Blueprint $table) {
$table->increments('id');
$table->integer('subject_id')->nullable();
$table->integer('teacher_id')->nullable();
$table->integer('user_id')->nullable();
$table->integer('effort')->nullable();
$table->timestamps();
});
Also have a table called 'Subject':
Schema::create('subjects', function(Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable();
$table->integer('studentID')->nullable();
$table->integer('teacherID')->nullable();
$table->integer('schoolID')->nullable();
$table->integer('memberID')->nullable();
$table->string('private')->nullable();
$table->integer('creator')->nullable();
$table->softDeletes();
$table->timestamps();
});
They are linked together like this in my model:
class Follow extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function subjects()
{
return $this->hasMany('Subject');
}
I like to filter the 'Item' list based on the 'Subjects' the 'User' is following. What would my Eloquent look like?
I have this filtering on the 'School' but I want to filter it on what the user is 'Following'
$follows = Follow::where('user_id', Auth::user()->id)->get();
$items = Item::where('school', Auth::user()->school)
->where('private', 'false')
->orderBy('created_at', 'DESC')
->get();

Resources