我如何加入Eloquent:人际关系? [英] How can I join with Eloquent: Relationships?

查看:91
本文介绍了我如何加入Eloquent:人际关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的查询是这样的:

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

从查询中,它可以按ID获取所有评论数据

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

我想要获取用户照片,商店照片和产品照片

I want get user photo, store photo and product photo

我想用雄辩的人际关系

我如何通过口才:关系?

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

我的产品型号如下:

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

推荐答案

如果您想从评论模型中查找产品并进行存储,请在Review模型中添加如下两种方法.

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

编辑App\Review.php

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,

$review遍历$reviews对象

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

这篇关于我如何加入Eloquent:人际关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆