Laravel 4:渴望加载(Laravel 4: Eager loading)

编程入门 行业动态 更新时间:2024-10-09 21:19:51
Laravel 4:渴望加载(Laravel 4: Eager loading)

我有一个名为UserWords的表,其中有一个word_id列,我想用它来获取Words表中的行,并将它们连接在一起,就像连接一样。 通过这种方式,每个人都可以从“ UserWords Words和“ Words获得行中的信息。 我在UserWord定义了这样的关系:

class UserWord extends Eloquent{ public function word(){ $this->belongsTo('Word'); } }

然后,我尝试获取所有的用户词和词,如下所示:

$words = UserWord::with("word")-> whereRaw("user_id = ".Auth::user()->id. " AND lang1 = '".$lang1. "' AND lang2 = '".$lang2."'") ->get();

如果我在那里没有with(),这是有效的。 那么,我做错了什么? 或者我将不得不创建一个原始JOIN来获得我想要的? 我从来没有做过关系,所以也许我在想这个根本错误? 无论哪种方式,请教我,而不只是给出答案,如果可以的话! 我阅读了文档,我认为它应该可以工作,但事实并非如此......我在这里问。

编辑:我得到的错误是:

Call to a member function addEagerConstraints() on a non-object

I have a table called UserWords that has a word_id column in it, and I want to use that to get the row from the Words table, and kind of concatenate them together like a join. This way each one will have the info from the row in UserWords and Words. I defined the relation like so in UserWord:

class UserWord extends Eloquent{ public function word(){ $this->belongsTo('Word'); } }

and then after that, I try to get all the UserWords and Words like so:

$words = UserWord::with("word")-> whereRaw("user_id = ".Auth::user()->id. " AND lang1 = '".$lang1. "' AND lang2 = '".$lang2."'") ->get();

This works if I don't have the with() in there. So, what am I doing wrong? Or am I going to have to create a raw JOIN to get what I want? I've never done relations before, so maybe I'm thinking of this fundamentally wrong? Either way, please teach me more than just giving the answer if you can! I read the docs and I think it should work, but it doesn't so... I'm asking here.

EDIT: The error I get is:

Call to a member function addEagerConstraints() on a non-object

最满意答案

您的关系的定义不正确,您必须返回belongsTo方法调用的结果。 尝试以下操作:

class UserWord extends Eloquent {
    public function word(){
        return $this->belongsTo('Word');
    }
}

The definition of your relation is not correct, you have to return the result of the belongsTo method call. Try the following:

class UserWord extends Eloquent {
    public function word(){
        return $this->belongsTo('Word');
    }
}

                    
                     
          

更多推荐

本文发布于:2023-04-29 08:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335610.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加载   Laravel   loading   Eager

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!