【问题标题】:Table Bring all comments for one article using yajra/laravel-datatables表格 使用 yajra/laravel-datatables 为一篇文章带来所有评论
【发布时间】:2017-03-06 22:52:30
【问题描述】:

当尝试获取Article::first() 但first() 的一篇文章的所有评论时 只带第一篇文章 我尝试使用find() 像

$comments = Article::find()-> commentsArticle()->with('articles');
return Datatables::of($comments)

我得到错误,所以我如何传递一个值来查看一篇文章的所有 cmets 要么 我有办法不用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

我希望找到任何类似的想法或例子可以帮助我学习

【问题讨论】:

    标签: laravel yajra-datatable


    【解决方案1】:

    您正在尝试使用其 cmets 获取第一篇文章。

    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
    

    评论和作者 获取评论作者姓名,需要在评论模型中定义关系

    public function user() {
        return $this->belongsTo(User::class);
    }
    

    那就这样吧

    if ( $article ) {
        return Datatables::of(Comment::with('users')->where('article_id', $article->id))->make(true);
    }
    

    【讨论】:

    • 现在很好,我认为我应该传递变量的路线如何
    • 以及如何通过“ajax”传递变量:'{{route(' route here')}}',
    • 首先,如果任何答案对您在 Stackoverflow 上有所帮助,您需要对其进行投票或将其标记为答案。现在对于您的其他问题,您需要学习基本路由:laravel.com/docs/5.4/routing#route-parameters 如果您遇到困难,我可以提供帮助,但请先尝试。我不会忘记投票并标记任何答案。谢谢。
    • 这是 StackOverflow 的第一次使用,老实说我不知道​​这里的卷,所以谢谢你的解决方案,谢谢你给我关于 Stackoverflow 的想法
    • 不客气。我为你添加了一些额外的内容。不是作为解决方案,而是作为 ajax 请求的指南。
    猜你喜欢
    • 2016-11-10
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    相关资源
    最近更新 更多