作者:零食君 | 来源:互联网 | 2023-01-23 17:19
为什么当我使用查询生成器而不是函数diffForHumans()时出现错误,但如果我使用ELoquent ROM但没有错误,有办法克服它?(我该怎么办呢)谢谢
diffForHumans()
这是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
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);
}
}
这是我的代码,我怎么能解决它?谢谢
1> yoeunes..:
我注意到你的代码中有几件事,
不需要演员created_at
和updated_at
日期,他们已经被铸造并且是实例Carbon
你可以使用该属性$casts
来构建简单的attributslive
无需为post_on
日期添加mutator,因为您将其添加到$dates
你也设置了一个mutator created_at
而不是post_on
,你用SetCreatedAttribute
而不是setPostOnAttribute
而不是substr($this->content,0,random_int(60,150))."..."
你可以使用str_limit
Laravel的辅助函数,也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()
你可以让你的模型更简单:
'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'));
}
2> Sazzadur Rah..:
默认情况下,eloquent将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();
这将以雄辩的方式给出理想的结果.