I'm hoping that I'm simply missing something, but I've spent a day trying to get this figured out on my own.
I'm working on trying to sync some tags
to a job
.
I've ran dd()
to make sure when submitting the tags are submitting as an array, and I've made sure my relationships are properly hooked up in laravel.
However, when creating a new job with tags (no tags works fine because the insert doesn't actually happen), this error comes up:
SQLSTATE[42000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]
Incorrect syntax near ','. (SQL: insert into [ninja_job_tag] ([job_id], [tag_id])
values (1, 1), (1, 3), (1, 5), (1, 7), (1, 8), (1, 10))
Here's the attach code ( $job
is properly created already):
$tagIDs = Input::get('tags') || [];
$job->tags()->attach(Input::get('tags'));
This is the function in Job.php
to call the tags
:
public function tags()
{
return $this->belongsToMany('App\Models\Marketing\Tag','ninja_job_tag');
}
This is the function in Tag.php
to call the jobs
:
public function jobs()
{
return $this->belongsToMany('App\Models\Marketing\Job','ninja_job_tag');
}
Here's the migration for the pivot table:
Schema::create('ninja_job_tag', function(Blueprint $table)
{
$table->integer('job_id')->unsigned()->index();
$table->foreign('job_id')->references('id')->on('ninja_jobs')->onDelete('cascade');
$table->integer('tag_id')->unsigned()->index();
$table->foreign('tag_id')->references('id')->on('ninja_tags')->onDelete('cascade');
});
Am I overlooking some stupid mistake? Thanks in advance for any help!
UPDATE
After some more investigating, adding only ONE tag works. This led me to look in a different direction, and I found that in order to insert multiple rows in one statement, the database MUST be ran by SQL Server 2008 or newer. It's unfortunate, but the server I need to run off of hasn't been updated in a long while and only runs SQL Server 2005 (version 9.0).
The only thing I can think of doing now is to use a foreach
to loop through EVERY tag_id
and attach them individually. Can anyone think of an alternate solution?
Laravel is set up (as it should) to send an insert
statement that will add multiple rows at once. The error comes up because the SQL Server version connected to is SQL Server 2005 (version 9.0), which does not support multiple rows in one insert
statement.
If you're having this problem, you'll need to do one of two things:
foreach
to attach the relationship PER relation: .
$tags = Input::get('tags');
foreach($tags as $tag){
$job->tags()->attach($tag);
}
This is an unfortunate workaround since you'll be running an execute statement for each relation being created, but unless a custom override for Eloquent
is created to use UNION
in the attach statements, this will have to do.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.