Laravel:通过id文章获取图像

时间:2014-07-21 19:34:04

标签: php laravel

我需要通过id文章获取图片。换句话说,在仪表板中我有显示标题文章,点击文章显示内容文章。一切都很好,除了显示图像。

我在数据库中有3个表: 用户 - 这里我有用户ID和姓名等。 文章 - 这里我有内容文章(标题,主要内容,日期等) 图像 - 这里我保存了每篇文章的图像(列:id,image_id,图像)

..接下来我有模特文章,图片,用户 在我的文章:

<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class Articles extends Eloquent implements UserInterface, RemindableInterface {
    use UserTrait, RemindableTrait;

    protected $table = 'articles';

    public $fillable = array(
        'id',
        'user_id',
        'subject'
    );

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

    public function itemsArticle() {
        return $this->hasMany('Image', 'id');
    }
}

在图像中我有:

<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class Image extends Eloquent implements UserInterface, RemindableInterface {
    use UserTrait, RemindableTrait;

    protected $table = 'image';

    public $fillable = array(
        'id',
        'image_id',
        'image',
    );

    public function apps() {
        return $this->belongs_to('User', 'id');
    }
}

和我的控制员:

$images = $this->data->itemsApp(); // here is maybe problem with show images from model Image
$articles = Articles::find($id);
return View::make('users.articles')
 ->with('images', $images)
 ->with('articles', $articles )

在view.blade中我使用foreach,如果结果只显示没有图像的内容文章。 谢谢你的建议。

1 个答案:

答案 0 :(得分:1)

您可能不需要此处的所有Illuminate类和接口。使用单数名称命名模型。

class Article extends Eloquent {

    public $fillable = array(
        'id',
        'user_id',
        'subject'
    );

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

    public function images() {
        return $this->hasMany('Image');
    }
}

并在您的图片模型中

class Image extends Eloquent {

    public $fillable = array(
        'id',
        'image_id',
        'image',
    );

    public function article() {
        return $this->belongsTo('Article');
    }
}

在您的images表格中添加字段整数article_id,您就可以通过

获取所有数据
$articles = Articles::with('images')->find($id);

return View::make('users.articles')->with('articles', $articles )

如果你想获得图片的用户电话

$image = Image::find($imageIdHere)->article()->user;
相关问题