How can I join with Eloquent: Relationships?

青春壹個敷衍的年華 提交于 2019-12-13 13:10:50

问题


My query is like this :

<?php
public function getListReviews()
{
    $reviews = Review::where('user_id', auth()->user()->id)
                     ->get();
    return $reviews;
}

From the query, it can get all review data by id

I want get user photo, store photo and product photo

I want get it use Eloquent: Relationships

How can I get it with Eloquent: Relationships?

My review model is like this :

<?php
namespace App;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use Jenssegers\Mongodb\Eloquent\HybridRelations;
class Review extends Eloquent
{
    use HybridRelations;
    protected $connection = 'mongodb';
    protected $fillable = ['user_id', 'user_name', 'product_id', 'product_name', 'store_id', 'store_name', 'invoice_number', 'rating', 'comments', 'created_at', 'updated_at'];
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

My user model is like this :

<?php
namespace App;
...
class User extends Authenticatable
{
    ...
    protected $fillable = ['name', 'email', 'password', 'birth_date', 'mobile_number', 'photo'];
    public function store()
    {
        return $this->hasOne(Store::class);
    }
}

My store model is like this :

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Store extends Model
{   
    protected $fillable = ['user_id', 'name', 'address', 'phones', 'total_product', 'photo'];
    public function products() 
    {
        return $this->hasMany(Product::class);
    }
}

My product model is like this :

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
    protected  $fillable = ['store_id','category_id','name', 'photo','description'];
    public function store()
    {
        return $this->belongsTo(Store::class);
    }
}

回答1:


If you want to find out product and store from review model then add two more methods to Review model as below.

Edit App\Review.php

//You already have key to to find store i.e. store_id
public function store()
{
    return $this->belongsTo(Store::class);
}


//You already have key to to find product i.e. product_id    
public function product()
{
    return $this->belongsTo(Product::class);
}

then execute your query as below

$reviews = Review::where('user_id', auth()->user()->id)
           ->with('store')
           ->with('product')
           ->with('user')
           ->get();

and you can access them as below,

Iterate through $reviews object as $review

$review->store->photo;
$review->product->photo;
$review->user->photo;


来源:https://stackoverflow.com/questions/42641789/how-can-i-join-with-eloquent-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!