2016-06-15 105 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,但在此有一个错字!