在将Anahkiasen/Polyglot包添加到我的Laravel 4.2项目中后,我试图让它发挥作用。我按照我认为应该的方式设置了所有内容(文档有点糟糕)。保存到数据库似乎不是问题,但当我想阅读时,我会收到以下错误:
Trying to get property of non-object (View: /Applications/MAMP/htdocs/*my view*.blade.php)
型号:
use Polyglot'Polyglot;
class Page extends Polyglot {
use SoftDeletingTrait;
protected $fillable = [
'lang',
'meta_title',
'meta_description',
'title',
'page_title',
'page_content',
];
protected $polyglot = [
'meta_title',
'meta_description',
'title',
'page_title',
'page_content',
];
// ...
}
class PageLang extends Eloquent {
public $timestamps = false;
protected $fillable = [
'page_id',
'lang',
'meta_title',
'meta_description',
'title',
'page_title',
'page_content',
];
}
我的刀片模板:
$page->nl->title
/*
This is what's causing the error
$page->title doesn't produce errors but is, of course, empty
*/
有一段时间了。非常感谢您的帮助:-)
我不熟悉这个库,但看看基本的Polyglot类,当你访问类似$page->nl
的东西时,这个抽象似乎是通过使用PHP的神奇__get
变量来注入n个本地化对象来实现的
看__get
,
public function __get($key)
{
// If the relation has been loaded already, return it
if (array_key_exists($key, $this->relations)) {
return $this->relations[$key];
}
// If the model supports the locale, load and return it
if (in_array($key, $this->getAvailable())) {
$relation = $this->hasOne($this->getLangClass())->whereLang($key);
if ($relation->getResults() === null) {
$relation = $this->hasOne($this->getLangClass())->whereLang(Config::get('polyglot::fallback'));
}
return $this->relations[$key] = $relation->getResults();
}
// If the attribute is set to be automatically localized
if ($this->polyglot) {
if (in_array($key, $this->polyglot)) {
/**
* If query executed with join and a property is already there
*/
if (isset($this->attributes[$key])) {
return $this->attributes[$key];
}
$lang = Lang::getLocale();
return $this->$lang ? $this->$lang->$key : null;
}
}
return parent::__get($key);
}
如果失败,有许多条件会导致父级的__get
被称为
return parent::__get($key);
换句话说,正常的模型行为。这可能就是上面发生的事情——由于nl
不是一个集合对象,当你试图调用它上的方法时,PHP会抱怨
在__get
中的三个条件句中,这似乎是失败的最可能候选者
if (in_array($key, $this->getAvailable())) {
$relation = $this->hasOne($this->getLangClass())->whereLang($key);
if ($relation->getResults() === null) {
$relation = $this->hasOne($this->getLangClass())->whereLang(Config::get('polyglot::fallback'));
}
return $this->relations[$key] = $relation->getResults();
}
如果你的具体情况,它看起来像
if (in_array('nl', $this->getAvailable())) {
//...
}
看getAvailable()
protected function getAvailable()
{
return Config::get('polyglot::locales');
}
它查找名为CCD_ 8的配置字段。我会检查调用该配置字段是否返回nl
作为配置的区域设置
var_dump(Config::get('polyglot::locales'));
我的猜测是没有,可能是因为你没有运行artisan命令来发布包的配置
php artisan config:publish anahkiasen/polyglot