简体   繁体   中英

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). So I need to make query like "SELECT * FROM Users, Message WHERE Users.email = Message.r_email. How can I do this?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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