为什么当我使用查询生成器时,函数diffForHumans ()上有一个错误,但是如果我使用ELoquent ROM,但是没有错误,就有办法克服它?(我怎样才能修好)谢谢
我是ArticlesController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Article;
use Carbon\Carbon;
use Auth;
use DB;
class ArticlesController extends Controller
{
public function index()
{
$articles =DB::table('articles')->get();
$articles = ['articles'=>$articles];
return view('articles.index',$articles);
}
}这是型号Article.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\SoftDeletes;
class Article extends Model
{
//
use SoftDeletes ;
protected $fillable = [
'user_id','content','live','post_on',
];
protected $dates =[
'post_on','deleted_at','created_at','updated_at',
];
public function setLiveAttribute($value)
{
$this->attributes['live'] = (boolean)($value);
}
public function getShortContentAttribute()
{
return substr($this->content,0,random_int(60,150))."...";
}
public function setPostOnAttribute($value)
{
$this->attributes['post_on'] = Carbon::parse($value);
}
public function setCreatedAtAttribute($value)
{
$this->attributes['post_on'] = Carbon::parse($value);
}
}这就是我的代码,我怎么能修正它?谢谢
发布于 2017-08-10 18:17:20
我注意到你的代码里有几件事,
created_at和updated_at转换为日期,它们已经被抛出并且是Carbon的实例。$casts来转换简单属性,如live。post_on日期添加变形器,因为您将它添加到$dates中created_at上而不是post_on上设置了一个mutator,您使用的是SetCreatedAttribute而不是setPostOnAttributesubstr($this->content,0,random_int(60,150))."...",您可以使用Laravel的str_limit助手函数,也可以将random_int更改为rand => int rand ( int $min , int $max )查询生成器将dates作为字符串返回,您需要在使用它们之前进行解析,否则会得到类似于此PHP error: Call to a member function on string的错误,只需这样做:
\Carbon\Carbon::parse(\DB::table('articles')->first()->post_on)->diffForHumans()您可以像这样简化您的模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Article extends Model
{
use SoftDeletes ;
protected $fillable = [
'user_id','content','live','post_on',
];
protected $dates = [
'post_on','deleted_at'
];
protected $casts = [
'live' => 'boolean'
];
public function getShortContentAttribute()
{
return str_limit($this->content, rand(60,150));
}
}您还可以简化index方法,如下所示:
public function index()
{
$articles = DB::table('articles')->get();
return view('articles.index', compact('articles'));
}发布于 2017-08-10 18:20:33
默认情况下,雄辩器将date/time字段作为Carbon实例返回,而查询生成器不返回。因此,如果要对查询生成器返回的属性使用Carbon,则必须使用Carbon::parse()方法包装属性。
例如,我可以将Carbon的一种方法toCookieString()用于有说服力的结果,如
echo App\User::find(1)->created_at->toCookieString();会给出像Thursday, 10-Aug-2017 17:59:53 UTC这样的反应。但是,如果我使用查询生成器而不是像
echo DB::table('users')->find(1)->created_at->toCookieString();那么它就会产生一个错误
调用字符串上的成员函数toCookieString()
为了在这里使用Carbon,我用Carbon的parse()方法包装了这个属性。
echo Carbon\Carbon::parse(DB::table('users')->find(1)->created_at)->toCookieString();这将使预期的结果成为雄辩。
https://stackoverflow.com/questions/45620330
复制相似问题