[英]Laravel 4.2 Array to String conversion error
我試圖基於URL字符串為我的模型中的$ table屬性分配一個值。 我收到“數組到字符串轉換”錯誤。 以下是代碼級別的詳細信息。 有人可以幫忙嗎? 謝謝。
我已經對模型__constructor()進行了編碼,如下所示。
<?php use Illuminate\\Auth\\UserTrait; use Illuminate\\Auth\\UserInterface; use Illuminate\\Auth\\Reminders\\RemindableTrait; use Illuminate\\Auth\\Reminders\\RemindableInterface; class Disaster extends Eloquent { use UserTrait, RemindableTrait; /** * The database table used by the model. * * @var string */ protected $table; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = array('password', 'remember_token'); public function __construct($disasterArea, $disaster = "flood") { $this->table = $disasterArea . '_' . $disaster; } }
我試圖從控制器中進行模型實例化時傳遞所需的值,如下所示。
class DisasterController extends \\BaseController { public function getFloodTweets($floodArea){ $flood = new Disaster($floodArea, "floods"); $floodTweets = $flood->orderBy('created_at','desc')->groupBy('tweets')->paginate(10); $floodAreaUc = ucfirst($floodArea); return View::make("disaster.floodTweets",['title'=>"$floodAreaUc Flood",'floodTweets'=>$floodTweets,'floodArea'=>$floodAreaUc]); } } }
這意味着,如果我觸發諸如www.example.com/floods/city之類的URL,我的模型應將表構建為“ city_floods”,這是我們遵循的命名約定。 而且,我觀察到表名正在正確構建,但是拋出此錯誤。 奇怪的是,當我對表名進行硬編碼時,我的代碼可以正常工作。 即
$ this-> table =“ city_floods”工作正常,但$ this-> table = $ disasterArea。 '_' $災難不會。 我不知道有什么區別。 有人可以建議我做錯了什么嗎?
我使用Laravel 4.2框架開發UBUNTU 14.04。
編輯
好吧,您不能以這種方式將數據傳遞給雄辯模型,因為原始的抽象雄辯模型的第一個參數為array
! 它將嘗試以這種方式進行說明。
編輯
從屏幕截圖中可以看到,該模型正在使用newInstance
方法解析某處,這意味着它試圖將(適當的)空數組放入字符串變量中。
解決方案
最好的選擇是將邏輯分解為幾個災難模型,以擴展主要的Disaster
模型並按如下方式在工廠中解決它們:
class UsaFloodDisaster extends Disaster
{
protected $table = 'usa_flood';
}
class FranceFloodDisaster extends Disaster
{
protected $table = 'france_flood';
}
(...)
class DisasterFactory
{
public function make($area, $disaster = 'flood')
{
$className = ucfirst(camel_case($area.'_'.$disaster));
return app($className);
}
}
那么您的控制器將如下所示:
class DisasterController extends \BaseController {
public function getFloodTweets($floodArea){
$flood = app(DisasterFactory::class)->make($floodArea, "floods");
$floodTweets = $flood->orderBy('created_at','desc')->groupBy('tweets')->paginate(10);
$floodAreaUc = ucfirst($floodArea);
return View::make("disaster.floodTweets",['title'=>"$floodAreaUc Flood",'floodTweets'=>$floodTweets,'floodArea'=>$floodAreaUc]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.