Laravel:从两个表中选择表2中的列=使用雄辩

时间:2016-12-06 13:13:06

标签: php mysql laravel

我有两张桌子 表1 = NewsCollection 表2 = NewsConllectionTranslation

这是模型

NewsCollection

class NewsCollection extends \Eloquent
{
    use \Dimsav\Translatable\Translatable;

    public $translatedAttributes = ['title', 'content'];
    public $translationModel = 'NewsCollectionTranslation';

    public function newsTrans()
    {
        return $this->hasMany('NewsCollectionTranslation', 'news_collection_id');
    }
}

NewsConllectionTranslation

class NewsCollectionTranslation extends \Eloquent
{
    public $timestamps = false;
    protected $table = 'news_collection_translations';
    protected $fillable = ['title', 'content'];

    public function transNews()
    {
        return $this->belongsTo('NewsCollection', 'news_collection_id');
    }
}

这是show controller

public function show($title)
    {
        $news = NewsConllectionTranslation::with('newsTrans')->where('title', $title)->first();
        return View::make('portal.news.show', compact('news'));
    }

我需要做的是

->where('title', $title)->first();

应该从NewsConllectionTranslation中选择,我不想丢失翻译,所以我不想先从NewsConllectionTrnslation中选择

2 个答案:

答案 0 :(得分:0)

像这样更改你的功能

 public function show($title)
    {
        $news = NewsConllectionTranslation::with(['newsTrans' => function ($query) use($title) {
                $query->where('title', $title)->first();
            }])


        return View::make('portal.news.show', compact('news'));
    }

答案 1 :(得分:0)

你应该试试这个:

$news = NewsConllectionTranslation::whereHas('newsTrans', function ($query) use ($title) {
    $query->where('title', $title);
})->first();