我使用laravel 5.2和试图建立一个多到一个国家,一个货币之间一对多的关系时,我收到以下错误:Laravel 5.2错误创建一个多对多的关系
ErrorException in helpers.php line 748:
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
我有以下定义多对多的关系,国家与货币模型:
class Country extends Model
{
protected $table = 'country';
protected $guarded = ['id'];
public function region()
{
return $this->belongsTo('App\Region');
}
public function destinations()
{
return $this->hasMany('App\Destination');
}
public function currencies()
{
return $this->belongsToMany('App\Currency', 'country_currency')->withTimestamps();
}
}
class Currency extends Model
{
protected $table = 'currency';
protected $fillable = ['name', 'code', 'sell_rate', 'buy_rate', 'min_denomenation', 'enabled'];
public function countries()
{
return $this->belongsToMany('App\Country', 'country_currency')->withTimestamps();
}
}
下面是我用添加国家(一个地区)的形式,您可以选择多种货币即得到发布与数组的一个片段我控制器方法:
<div class="col-xs-12 col-sm-6 col-md-3 form-group">
<label for="currencies">Currency: </label>
<select class="form-control" name="currencies[]" id="currencies" multiple>
@foreach($currencies as $currency)
<option value="{{$currency->id}}">{{$currency->name}} </option>
@endforeach
</select>
</div>
我CountryController与createCountry方法如下表单时发布被称为:
class CountryController extends Controller
{
public function add(Region $region)
{
$currencies = Currency::all(['id', 'name']);
return view('admin.destinationeditor.country.add', compact('region', 'currencies'));
}
public function createCountry(CountryRequest $request, Region $region)
{
$country = $region->countries()->create($request->all());
$currencyIds = $request->input('currencies');
$country->currencies()->attach($currencyIds);
flash()->success('Success!', 'The country page was successfully added to the region');
return redirect()->back();
}
}
的问题是似乎出现时,我通过$currencyIds
到attach()
方法。
如果我没有发布任何货币,我们创建的国家没有问题,但是当我尝试发布货币值时,就会出现问题。
有没有人有任何想法如何解决这个问题?
干杯, 吉姆
您可以尝试使用** sync **而不是** attach **并查看是否得到相同的错误。 – TheFallen
@TheFallen我刚刚给出了一个尝试,但同样的错误正在发生 – user2286026
你可以var_dump'$ currencyIds'并查看它是否是一维数组? – TheFallen