当试图让所有评论一个文章Article::first()
,但first()
只带了第一篇文章中我尝试使用find()
类似
$comments = Article::find()-> commentsArticle()->with('articles');
return Datatables::of($comments)
我收到错误,所以我如何传递一个值来查看一篇文章的所有评论,或者我可以不使用 find()
文章模型
class Article extends Model{
public $table = 'articles';
public function commentsArticle() {
return $this->hasMany('App\Comment');
}
}
控制器
enter code here
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Yajra\Datatables\Datatables;
use App\Article;
use App\Comment;
class CommentController extends Controller{
public function commentsForOne Article()
{
$comments = Article::all()->commentsArticle->with('articles');
return Datatables::of($comments)->make(true);
}
}
我得到的最后一个错误
ErrorException (E_DEPRECATED)
Non-static method Yajra\Datatables\Datatables::collection() should
not be called statically
我希望能找到任何类似的想法或例子来帮助我学习
您正在尝试获取带有评论的第一篇文章。
public function commentsForOneArticle($id)
{
$article = Article::fine($id);
//check if article exists to avoid errors
if ( $article ) {
return Datatables::of(Comment::where('article_id', $article->id))->make(true);
}
return "no article with id" . $id;
}
这只是一个例证。但似乎您首先需要了解 Eloquent 的工作原理。观看免费的Laracast https://laracasts.com/series/laravel-from-scratch-2017/episodes/7
对于路由,您可以像这样定义路由:
Route::get('comments/{article_id}', 'ArticleController@commentsForOneArticle');
并在 Ajax 中调用它
$.ajax({url: "/comments/1",
success: function(result){
//do stuff here
},
error: function(error) {
console.log(error)
}
});
所有这些只是一个指南,而不是解决方案。
编辑
与用户一次性获取数据
$article = Article::with('user')->find($id);
//will include all the fields from user and article
Comments & author要获得评论作者的名字,需要在评论模型中定义关系
public function user() {
return $this->belongsTo(User::class);
}
然后变成这样
if ( $article ) {
return Datatables::of(Comment::with('users')->where('article_id', $article->id))->make(true);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句