gpt4 book ai didi

php - Laravel 属于/有很多

转载 作者:行者123 更新时间:2023-12-02 17:37:30 26 4
gpt4 key购买 nike

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

所以简短的描述:

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

五月表结构

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

我的图库模型:

<?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');
}

还有我的博物馆 Controller

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

最佳答案

你可以试试这个:

// 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');
}

然后在 Controller 中:

$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

关于php - Laravel 属于/有很多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25219798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com