简体   繁体   English

如何使用laravel查询构建器正确构建查询?

[英]How can I construct query with laravel query builder correctly?

I have two models: Users and Message. 我有两个模型:用户和消息。 They are bound together with relation one to many (one user can send many messages). 它们以一对多关系绑定在一起(一个用户可以发送许多消息)。 Table Users has a column "email" and table Message has column "r_email" (this is the same field). 表用户具有“电子邮件”列,表消息具有“ r_email”列(这是同一字段)。 So I need to make query like "SELECT * FROM Users, Message WHERE Users.email = Message.r_email. How can I do this? 因此,我需要进行如下查询:“ SELECT * FROM Users,消息WHERE Users.email = Message.r_email。我该怎么做?

I tried something like this: 我尝试过这样的事情:

 $messages = App\Message::with('users')->where('users.email', '=', 'messages.r_email')->get();

But it gives me Error. 但这给了我错误。 What is a problem? 怎么了

Models are bound in this way: 模型是通过以下方式绑定的:

class User extends Authenticatable
{
use Notifiable;

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

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'email_verified_at' => 'datetime',
];

public function messages()
{
    return $this->hasMany(Message::class);
}
}

And the code for Message model: 以及消息模型的代码:

class Message extends Model
{
    protected $fillable = ['message', 'r_email'];
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

尝试

$messages = App\Message::with('users')->whereRaw('users.email = messages.r_email')->get();

Try this 尝试这个

$messages = DB::table('users')
 ->leftJoin('message', 'users.email', '=', 'message.r_email')
 ->get();

Hope this help. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM