如何在Laravel 5.2中使用paginate与关系?(How to use paginate with relationships in Laravel 5.2?)

我试图通过使用关系从数据库中选择数据时使用paginate 。 我有三个表,即userscontactscontact_messages ,分别是UserContactContactMessage

我试图通过使用以下方法获取特定用户的所有消息:

public function listMessage($user_id){
        $user1 = User::find($user_id);
        $messages = $user1->contact_messages;
        return View::make('message.listmessage')
        ->with('user_id', $user_id)
        ->with('messages', $messages);
    }

通过这种方法,我收到所有消息,但我无法对$messages分页。 我如何分页$messages ? 有人可以帮忙吗?

我的模型和关系如下:

class User extends Authenticatable
{
    public function contacts()
    {
        return $this->hasMany('App\Contact');
    }
    public function contact_messages()
    {
        return $this->hasManyThrough('App\ContactMessage', 'App\Contact');
    }
}

和联系模式是

class Contact extends Model
{
    public function user(){
        return $this->belongsTo('App\User');
    }

    public function messages()
    {
        return $this->hasMany('App\ContactMessage');
    }
}

最后ContactMessage模型是

class ContactMessage extends Model
{
    public function contact(){
        return $this->belongsTo('App\Contact');
    }
}

I am trying to use paginate while selecting data from database by using relationships. I have three tables namely, users, contacts and contact_messages with models User, Contact, ContactMessage respectively.

I am trying to fetch all messages of a particular user by using the following method :

public function listMessage($user_id){
        $user1 = User::find($user_id);
        $messages = $user1->contact_messages;
        return View::make('message.listmessage')
        ->with('user_id', $user_id)
        ->with('messages', $messages);
    }

By this method I am getting all messages, but I couldn't paginate $messages . How can I paginate $messages? Can anyone help?

My models and relationships are given below :

class User extends Authenticatable
{
    public function contacts()
    {
        return $this->hasMany('App\Contact');
    }
    public function contact_messages()
    {
        return $this->hasManyThrough('App\ContactMessage', 'App\Contact');
    }
}

and Contact Model is

class Contact extends Model
{
    public function user(){
        return $this->belongsTo('App\User');
    }

    public function messages()
    {
        return $this->hasMany('App\ContactMessage');
    }
}

finally ContactMessage model is

class ContactMessage extends Model
{
    public function contact(){
        return $this->belongsTo('App\Contact');
    }
}

原文:https://stackoverflow.com/questions/38741266
2024-05-07 20:05

满意答案

最后想出了这一点,部分得到了Adam 在这里的回答。

在我的控制器的show动作中,我将块更改为:

@order.each do |order|
  order.fillforms(order.id, agent)
end

Order模型中,我将fillforms方法的前两行更改为:

def fillforms(order_id, agent)
  order = Order.find(order_id)

现在,Mechanize进入块,因此块正确执行。


Finally figured this out, helped in part by Adam's answer here.

In my controller's show action, I changed the block to:

@order.each do |order|
  order.fillforms(order.id, agent)
end

And in the Order model, I changed the first two lines of the fillforms method to:

def fillforms(order_id, agent)
  order = Order.find(order_id)

Now Mechanize follows into the block, and the block consequently executes properly.

相关问答

更多

如何使用Mechanize填充dom节点输入的值?(How do I fill the value of a dom node input with Mechanize?)

更改行input.value = "2010" 至 input['value'] = "2010" type , name等是input元素的属性。 您需要使用Nokogiri::XML::Node#[]=方法。 阅读[]=(name, value)的文档 将属性名称的属性值设置为value 示例: require 'nokogiri' doc = Nokogiri::XML <<-xml <foo atr = '123'> test </foo> xml doc.at('foo')['at...

在Google文档中使用Mechanize(Using Mechanize with Google Docs)

安迪,你真棒! 您的代码帮助我使我的脚本可行并登录到Google帐户。 几个小时后我发现了你的错误。它是关于html转义的。 正如我发现的那样,Mechanize会自动转义它作为'get'方法的参数。 所以我的解决方案是: EMAIL = ".." PASSWD = ".." agent = Mechanize.new{ |a| a.log = Logger.new("mech.log")} agent.user_agent_alias = 'Linux Mozilla' agent.open_...

Mechanize Link#click vs Agent#get(Mechanize Link#click vs Agent#get)

看看这里有什么点击 。 它调用get ,但首先设置引用并进行一些机器人检查。 The problem turned out not to be a difference between Link#click and Agent#get, but the server had changed its response in certain situations. In other words, my assumptions were wrong.

使用来自控制器的Mechanize代理进入模型方法(Having Mechanize agent from controller follow into model method)

最后想出了这一点,部分得到了Adam 在这里的回答。 在我的控制器的show动作中,我将块更改为: @order.each do |order| order.fillforms(order.id, agent) end 在Order模型中,我将fillforms方法的前两行更改为: def fillforms(order_id, agent) order = Order.find(order_id) 现在,Mechanize进入块,因此块正确执行。 Finally figured th...

WWW :: Mechanize关注链接无法找到链接(WWW::Mechanize follow link can't find link)

您需要在您的网址前加上$dir 。 而不是使用follow_link()您指定URL的follow_link() ,只需使用另一个get() : $mech->get( "file:$dir/" . $link->url() ); You need to prepend $dir to your URL. Instead of using follow_link(), which won't let you specify the URL, simply use another get(): $...

class << self,alias_method和monkey patching Mechanize :: Cookie(class << self, alias_method, and monkey patching Mechanize::Cookie)

yield cookie if block_given?看起来原始的解析方法有一个yield cookie if block_given? 声明。 你也需要能够传递一个块。 编辑: 更清楚...... class Foo def self.x yield "yielded from x!" if block_given? end end class Foo class <<self alias :y :x end # new...

Ruby Mechanize 404 => Net :: HTTPNotFound(Ruby Mechanize 404 => Net::HTTPNotFound)

好, 问题是该网站禁用了Mechanize用户代理。 我刚将其更改为: mechanize.user_agent_alias = 'Windows Chrome' Ok, The problème was that the website disable the Mechanize user agent. I just changed it to : mechanize.user_agent_alias = 'Windows Chrome'

Ruby Mechanize,Nokogiri和Net :: HTTP(Ruby Mechanize, Nokogiri and Net::HTTP)

我不确定你为什么认为使用Net :: HTTP会更好。 Mechanize将处理重定向和cookie,并提供对Nokogiri解析文档的随时访问。 require 'mechanize' agent = Mechanize.new page = agent.get('http://www.example.com') # Use Nokogiri to find the content of the <h1> tag... puts page.at('h1').content # => "Exa...

Mechanize和HTTParty中的“主机名与服务器证书不匹配”错误(“Hostname does not match the server certificate” error in Mechanize and HTTParty)

对于Mechanize,应将SSL验证为none agent = Mechanize.new agent.verify_mode = OpenSSL::SSL::VERIFY_NONE 对于HTTParty,有verify:选项请参阅此问题如何使HTTParty忽略SSL? 如果你想一般地设置它,使用这个脏技巧: OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE For Mechanize this should set verify ...

为什么Mechanize没有关注链接(Why is Mechanize not following the link)

您应该获取Charles( http://www.charlesproxy.com/ )的副本,或者允许您查看从浏览器提交表单时发生的情况。 无论如何,你的问题是这部分: agent.page.forms[0]["lookup_text"] = "VG278H" agent.page.forms[0].submit 正在返回一个看起来像这样的html片段: <meta http-equiv="Content-Type" content="text/html; charset=utf-8"><sc...

相关文章

更多

LARAVEL学习--安装

  之前一直使用Codeignitor框架进行PHP的开发,Codeignitor是一个非常优秀的框架 ...

微信5.2

微信5.1刚刚发布还没多久,官方就已经开始Android版的微信5.2内测了,尽管还只是一个内测版,但 ...

微信5.2

微信5.1刚刚发布还没多久,官方就已经开始Android版的微信5.2内测了,尽管还只是一个内测版,但 ...

CentOS5.2下使用Ganglia对Hadoop进行监控

Ganglia是一个监控服务器,集群的开源软件,能够用曲线图表现最近一个小时,最近一天,最近一周,最近 ...

RHEL 5.2下的Hadoop分布式集群环境搭建文档

一、 前言 偶然间同学跟我谈到Hadoop分布式集群,恰好同学也需要自己去搭建hadoop平台,因此我 ...

【第五章】Spring表达式语言 之 5.1 概述 5.2 SpEL基础 ——跟我学spring3

Spring表达式语言全称为“Spring Expression Language”,缩写为“SpEL ...

如何在rails中使用支付宝

谁能给详细说一下。 有没有什么开源项目已经实现这块功能,或是有现在的代码可以参考?

如何在jsf标签中使用java的枚举类型

在后台Java对象中有个枚举类型属性,例如学生的学科用枚举类型表示 class Student { ...

如何在 ListView 中显示 RadioButton???

因为看到可以在 ListView 中显示 ImageView, TextView, Checkbox ...

如何在SOLR中嵌入自己的分词系统??

SOLR虽然为我们提供了分词的接入方法,但很显然并不奏效,搜遍了大江南北,也没有什么可参考的,大部分都 ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本