【问题标题】:Extremely New at Laravel, have tried to use Examples, but no goLaravel 非常新,尝试使用示例,但没有成功
【发布时间】:2014-01-21 02:23:10
【问题描述】:

我认为这将是 hashasMany 和 belongsTo 的简单用法,但我没有获取我的一个表的数据,即标题。

我有两张桌子:

scenes  ( movie scenes basically)
------
int scene_id  (can't change to "id".. this is at my company)
string scene_name

int title_id


titles  (movie dvd titles)
------
int title_id    ( same here.. should be id, but it's not )
string title_name
string title_description

“场景”表中有多个场景,具有相同的 title_id,您可能已经猜到了。

到目前为止,我有:

class Title extends Eloquent {
    protected $table = 'titles';
    protected $primaryKey = "title_id";

    public function scenes() {

        return $this->hasMany('Scene','title_id','title_id');

    }

}

class Scene extends Eloquent {
    protected $table = 'scenes';
    protected $primaryKey = "scene_id";

    public function title() {

        return $this->belongsTo('Title', 'title_id', 'title_id');
    }
}

在我看来,我必须为 title() 和 Scenes() 成员函数指定 title_id。但该字段将每个标题与其多个场景连接起来。

我为获得一个场景(假设 $scene_id 是一个 int)以及每个场景的标题信息而进行的调用是:

$scene_info = Scene::find($scene_id)->title(); 

如果我对 $scene_info 执行 var_dump,我会得到 很多 的 Laravel 代码,我猜我不应该这样做。
我也得到了场景信息,但是标题信息是空白的。

只是想知道我的 Laravel 编码是否有问题

史蒂夫

【问题讨论】:

  • 请向我们展示此lot of Laravel code 的前三行,这将有助于人们了解您所得到的。
  • 抱歉,在我发布这个问题时我没有看到您的评论。我会发布该信息的。

标签: laravel laravel-4


【解决方案1】:

尝试以下方法:

$scene_info = Scene::with('title')->find($scene_id); 

或者你可以在拿到场景后懒加载关系:

$scene_info = Scene::find($scene_id); 

$scene_info->load('title');

【讨论】:

  • 感谢 Anam,做到了(仅尝试了第一个)。获取两个数据副本是否正常: ["attributes":protected]=> array(37) { 和 ["original":protected]=> array(37) { @Antonio - 不再将 Laravel 库嵌入物体。 Anam 的解决方案就是它
  • 是的,您将获得包括关系在内的数据。例如,如果您的 Scene 模型有任何其他关系,您以后甚至可以从视图中使用它们。
  • 我想知道实际检索数据的最佳方法是什么。我使用上面的第一个选项 ($scene_info = Scene::with('title')->find($scene_id); ),当我使用 getOriginal() 或 getAttributes() 时,我只使用场景中的数据表,而不是标题。如果我不使用 getXXX,而只是尝试手动获取数据,则元素键的“::protected”部分会阻止我获取数据。
【解决方案2】:

终于找到了获取标题信息所需的东西:

原来如此:

$info = Scene::with('title')->find($scene_id); (thanks to Anam)

// to get scene info
$scene_array = $info->getAttributes();

// to get title info
$title_array = $info->getRelations();

您会认为,如果您在第一次调用时已经指定了“ ('title') ”,那么调用 getRelations() 将不需要获取标题信息。

无论如何,再次感谢你们的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 2021-02-07
    • 2016-03-16
    • 1970-01-01
    相关资源
    最近更新 更多