2016-06-15 104 views
0

我使用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(); 
    } 

}

的問題是似乎出現時,我通過$currencyIdsattach()方法。

如果我沒有發佈任何貨幣,我們創建的國家沒有問題,但是當我嘗試發佈貨幣值時,就會出現問題。

有沒有人有任何想法如何解決這個問題?

乾杯, 吉姆

+0

您可以嘗試使用** sync **而不是** attach **並查看是否得到相同的錯誤。 – TheFallen

+0

@TheFallen我剛剛給出了一個嘗試,但同樣的錯誤正在發生 – user2286026

+0

你可以var_dump'$ currencyIds'並查看它是否是一維數組? – TheFallen

回答

0

你能創建既貨幣模型和國家模型關係函數試試?我的意思是你已經創建了國家模型的功能,但還沒有創建任何從貨幣模型。我不知道兄弟,但你可以檢查。 :) :)

+0

感謝您的評論。我從另一個表格創建貨幣模型,他們正在創建罰款。只是當我將這些貨幣匯入國家形式並試圖將它們聯繫起來時,我正在遇到這個問題。 – user2286026

+0

你是最受歡迎的:) :) – Sakil

0

我設法得到這個問題的底部。我將$guarded財產更改爲$fillable,但在此有一個錯字!