我使用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