【问题标题】:Laravel belongsTo / hasManyLaravel 属于To / hasMany
【发布时间】:2014-08-09 14:54:32
【问题描述】:

我有一个问题,我需要获取我的画廊表中拥有博物馆和拥有博物馆的用户的所有图像(路径)。 我得到了图像的路径,但这些与拥有博物馆的 user_id 无关。

所以简短的描述:

每个用户都拥有一个博物馆,一个博物馆有一个包含多张图片的画廊(图片网址的路径)

五月表结构

  • 博物馆
    • 身份证
    • 标题
    • user_id
  • 用户
    • 身份证
    • 电子邮件
    • 密码
  • 图库
    • 身份证
    • museum_id
    • 标题
    • 路径

我的画廊模型:

<?php

class Gallery extends \Eloquent {

protected $fillable = [];

public function museums() {
    //return $this->belongsToMany('Museums', 'id');
    return $this->belongsTo('Gallery', 'museum_id');
}
}

我的博物馆模型

<?php

class Museum extends Eloquent {

protected $fillable = ['user_id', 'title', 'description'];

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

public function gallery()
{
    //return $this->belongsToMany('Gallery', 'museum_id');
    return $this->belongsToMany('Gallery');
}

}

我的用户模型

public function museums()
{
    return $this->hasMany('Museum');
}

还有我的博物馆控制器

public function show($id)
{
    //
    //$museum = Museum::where('id', '=', $id)->first();
    //return View::make('museums.detail', compact('museum'));
    $museum = Museum::findOrFail($id);
    $gallery = Gallery::with('museums')->get();
    //$museum = Museum::with('gallery')->get();

    return View::make('museums.detail', compact('museum', 'gallery'));
}

在我看来我有

@foreach ($gallery as $image)
<img src="{{ $image->path }}" />
@endforeach

【问题讨论】:

  • 什么是异常信息?或者你得到了什么?

标签: php laravel


【解决方案1】:

你可以试试这个:

// In User model
public function museum()
{
    return $this->hasOne('Museum');
}

// In Museum model
public function owner()
{
    return $this->belongsTo('User');
}

// In Museum model
public function galleries()
{
    return $this->hasMany('Gallery');
}

// In Gallery model
public function museum()
{
    return $this->belongsTo('Museum');
}

然后在控制器中:

$museums = Museum::with('galleries', 'owner')->get();
return View::make('museums.detail', compact('museums'));

在你看来:

@foreach ($museums as $museum)

    {{ $museum->title }}

    // To get the user id from here
    {{ $museum->owner->id }}

    // Loop all images in this museum
    @foreach($museum->galleries as $image)

        <img src="{{ $image->path }}" />

        // To get the user id from here
        {{ $image->museum->owner->id }}

    @endforeach

@endforeach

【讨论】:

  • 使用您的解决方案,我得到错误 Trying to get property of non-object (View: /home/vagrant/code/museum/app/views/museums/detail.blade.php)
  • “视图”代码中有错字。 @foreach($museum->gelleries .... 应该是画廊。
猜你喜欢
  • 2017-10-08
  • 1970-01-01
  • 2016-09-28
  • 1970-01-01
  • 2019-08-12
  • 1970-01-01
  • 2015-12-16
  • 2018-07-17
  • 1970-01-01
相关资源
最近更新 更多