【问题标题】:Laravel - how to change table in orWhere method?Laravel - 如何在 orWhere 方法中更改表格?
【发布时间】:2016-06-18 15:13:17
【问题描述】:

我想做这样的事情:

$posts= Status::where('users_id',$user->id)->orWhere(DB::table('user_status_share.user_id', $user->id))->orderBy('created_at', 'DESC')->get();

但我得到一个错误:strtolower() 期望参数 1 是字符串,给定对象 - 如何在“orWhere”方法中更改表格?这可能吗?如果不是 - 如何在一个查询中使用 2 个表?

架构(状态):

public function up()
{
    Schema::create('users_status', function (Blueprint $table) {
        $table->increments('id')->unique();
        $table->longText('status_text');
        $table->integer('users_id')->unsigned();
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('users_status');
}

架构(StatusShare):

public function up()
{
    Schema::create('user_status_share', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('status_id');
        $table->integer('user_id');
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('user_status_share');
}

模型状态:

namespace App\Eloquent;

use Illuminate\Database\Eloquent\Model;

class Status extends Model
{
    public $timestamps = true;
    protected $table = 'users_status';
    protected $guarded = ['id'];

    public function comments()
    {
        return $this->hasMany(StatusComments::class);
    }

    public function likes()
    {
        return $this->hasMany(StatusLikes::class);
    }

    public function shares()
    {
        return $this->hasMany(StatusShare::class);
    }

}

模型状态共享:

<?php

namespace App\Eloquent;

use Illuminate\Database\Eloquent\Model;

class StatusShare extends Model
{
    public $timestamps = true;
    protected $table = 'user_status_share';
    protected $guarded = ['id'];

    public function status()
    {
        return $this->hasOne(Status::class);
    }
}

【问题讨论】:

  • 你想从两个表中获取数据吗?
  • 请在输出中发布您的架构结构和您期望的数据格式。
  • 是的,我想从 2 个表中获取数据
  • 添加了架构。我期待数组

标签: php mysql laravel


【解决方案1】:

我认为你应该尝试这样的事情

调整一下,我没测试过

 $posts = DB::table('status')->where('users_id',$user->id)->orWhere(function ($query) use ($user) {
                $query->table('user_status_share')->where('user_id', $user->id);
            })
            ->get();

您能否分享更多信息,因为我觉得可以使用关系以简单的方式获得这些信息(向我们展示您的模型中的数据库结构和关系)

【讨论】:

  • 感谢您的评论,但这给了我一个错误“调用未定义的方法 Illuminate\Database\Query\Builder::table()”。
猜你喜欢
  • 2021-10-10
  • 2015-01-06
  • 2021-03-11
  • 2016-10-20
  • 2015-08-29
  • 2020-08-14
  • 1970-01-01
  • 2015-02-22
  • 2016-04-23
相关资源
最近更新 更多