【问题标题】:How to add multiple table relationship in laravel如何在laravel中添加多表关系
【发布时间】:2018-12-30 02:08:44
【问题描述】:

我有以下表格并使用 Laravel 关系构建查询。在我的面板中,一旦用户登录,我就会获取用户详细信息和用户业务详细信息,但现在我也不知道如何获取业务类型详细信息。

用户表:

id | business_id | username | email          | password
1    1             john632    john@gmail.com   *******

用户业务表

id | user_id | business_type_id | business_name
1    1         2                  Fortune

业务类型表

id | business_type_name | description
1    Hotel                Lorem Ipsum
2    Movie                Lorem Ipsum

型号:

用户

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use App\Notifications\ResetPassword as ResetPasswordNotification;
use Laravel\Passport\HasApiTokens;
use Illuminate\Database\Eloquent\SoftDeletes;
use Webpatser\Uuid\Uuid;
use App\RoleUser;
use App\UsersBusiness;

class User extends Authenticatable
{
    use Notifiable;
    use EntrustUserTrait;
    use HasApiTokens;
    use SoftDeletes, EntrustUserTrait {
        SoftDeletes::restore as sfRestore;
        EntrustUserTrait::restore as euRestore;
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'business_id', 'username', 'email'
    ];

    public function usersBusiness()
    {
        return $this->belongsTo('App\UsersBusiness', 'business_id', 'id');
    }
}

UsersBusiness

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class UsersBusiness extends Model
{
    use SoftDeletes;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'tbl_users_business';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', 'business_type_id', 'business_name'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [

    ];

    /**
     * Dates to be treated as Carbon instances
     *
     * @var array
     */
    public $dates = [
        'deleted_at'
    ];
}

业务类型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class BusinessTypes extends Model
{
    use SoftDeletes;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'tbl_master_business_types';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'business_type_name', 'description'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [

    ];

    /**
     * Dates to be treated as Carbon instances
     *
     * @var array
     */
    public $dates = [
        'deleted_at'
    ];
}

代码:

$user = Auth::user();
$data['data'] = $user->load(['usersBusiness'] => function ($query) {
    $query->select(["id", "user_id", "business_name"])->get();
}]);

我得到以下响应数据:

{
    "data": {
        "id": 1,
        "business_id": 1,
        "username": "john632",
        "email": "john632@gmail.com",
        "password": "john632",
        "users_business": {
            "id": 1,
            "user_id": 4,
            "business_type_id": 3,
            "business_name": "Honest"
        },
        "business_types": null
    },
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6Ijk4YTQ5OTBmOGQxOWQ5NTg1OGFlZWU1MDY0NTBiY2Y2OWJmOWQ3NzFhZjRmN2RmMzBmMWRkZWNmNWY4OTAzM2UyNmI2MzE3MTY3MDMxOTk4In0.eyJhdWQiOiIxIiwianRpIjoiOThhNDk5MGY4ZDE5ZDk1ODU4YWVlZTUwNjQ1MGJjZjY5YmY5ZDc3MWFmNGY3ZGYzMGYxZGRlY2Y1Zjg5MDMzZTI2YjYzMTcxNjcwMzE5OTgiLCJpYXQiOjE1MzIyNjA3ODUsIm5iZiI6MTUzMjI2MDc4NSwiZXhwIjoxNTYzNzk2Nzg1LCJzdWIiOiI1Iiwic2NvcGVzIjpbXX0.f_Xv0SrtTZ9m-40oHjAglCbKv76s_bARQ74XDihhFnI-jtHKwCWiF-jai5Yt6h9QyakCTZEo1bPAJdeph7Bj0_tKJpq3sGvK4t73_LZg_OOcsmAt61a4OSAgI1pjPV0tMMwHCoHm-xLlNnriAyaLCAbTQLQkfrw53467ys6rchE5V0rzy-JswjTfmB6SvZcqXsJQo6CWDRTWYbKvJO0FSmdZfLxxO_u4i_8ah5W63qJ4MSN9q22zkZLQ-L3NZhOux2KkwWiySioL2K25Y_UZmefClYwk1h-EY_LEVht3U7Kpqn9fmM6_Q4ByD-sSzLdAixdbq4REqinSaayzfMY934nijLu7ysEIc0oIukiHYcIk9tGV6DNuQ0CWhqEn0W_308MSBU4Ffyi5SQo7ubb5uPG7l_XOdomIR9dK9KtVONbPe7iF6TuccPCWZwvqKgfFl7TqEgiUWSiAl_ekkiaUDEM3cIuIH8AOLE17UuW4W0VyR2ziIt68au8SEuP2ilMBRsRMsFGbRKQWcvLluNw_qubcdzZ4yX9kuQAvXuBrHAcXb9WMlki2votvd7RKVDwxqwsTJRoeKNtJQdEQRbRZUD6nXyzGkmtEMrfwYoLVgTX3vAgVjO_erYtI5x-NV-EnoLT352odtRDYh5gTzVbmzYAxbLf_XUCDHjvlMEvM81g",
    "status": true,
    "status_code": 1,
    "message": "Login successfully."
}

我也想添加业务类型详细信息,请指导我如何为该表添加关系。

谢谢。

【问题讨论】:

  • 你有UserBusiness模特吗?
  • @rkj 是的。我为每个表创建了模型。我已经更新了我的问题。
  • 我已经添加了答案检查它
  • 您的用户模型与业务的关系很好,只需在 UsersBusiness 中添加一个关系即可完成
  • 为什么要在 userbusiness 表中添加 user_id 而在 user 表中添加 business_id ?我认为您不需要用户表中的business_id。只需将 user_id 保留在 userbusiness 表中,然后在 User 模型中添加 'hasOne` 或 hasMany 关系

标签: laravel eloquent


【解决方案1】:

像这样在 UserBusiness 模型中创建一个 belongsTo 关系

用户业务模型

public function businessType(){
     return $this->belongsTo(BusinessType::class, 'business_type_id');
}

然后像这样加载它

$user = Auth::user();
$user->load(['usersBusiness.businessType']); //lazy loading
dd($user);

如果您只需要 userBusiness 及其类型

dd($user->usersBusiness);

旁注:我认为您不需要在 users 表中使用 business_id。只需将user_id 保留在userbusiness 表中,然后在userBusness 的用户模型中添加hasOne(如果用户只能拥有一项业务)或hasMany(如果用户可以拥有多个业务)关系。

【讨论】:

    【解决方案2】:

    我推荐你使用API Resources.

    例如,就我而言,我有 ChannelItemResource.php

    public function toArray($request)
        {
            return [
        'id' => $this->id,
        'channel_id' => $this->channel_id,
        'channel' => $this->channel->title,
        'type' => $this->type,
        'description' => $this->description,
        'price' => $this->price,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];
        }
    

    ChannelResource.php

    return [
        'id' => $this->id,
        'title' => $this->title,
        'user_id' => $this->user_id,
        'description' => $this->description,
        'type' => $this->type,
        'url' => $this->url,
        'ranking_total' => $this->ranking_total,
        'ranking_flag' => $this->ranking_flag,
        'ranking_country' => $this->ranking_country,
        'thumbnail' => $this->thumbnail,
        'state' => $this->state,
        'hit' => $this->hit,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
        'items' => ChannelItemResource::collection($this->items),
    ];
    

    使用这种结构,您可以轻松地包含所需的关系,结果将以 JSON 格式显示。

    控制器中使用:

    public function all(Request $request)
        {
            return new ChannelsResource(Channel::where("state", "active")->orderBy('id', 'desc')->paginate(30));
        }
    

    【讨论】:

      猜你喜欢
      • 2012-12-07
      • 1970-01-01
      • 2014-10-09
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      相关资源
      最近更新 更多