查询适用于 MySQL workbench 但不适用于 Laravel

Query works on MySQL workbench but not on Laravel

我一直在使用数据库中的正文在 Laravel 上发送邮件,一切正常,直到我在 laravel 查询中添加连接函数。当我在 MySQL workbench 上输入查询时,我按预期返回了一行,但没有 laravel.

Welcome.php :

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class Welcome extends Mailable
{
    use Queueable, SerializesModels;

     
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->from('xxxxxx@yyy.com', 'John Doe')
            ->subject('Welcome')
            ->markdown('mails.welcome')
            ->with([
                'name' => 'New User',
                'wMail' => DB::table('mails')
                            ->join('users', 'mails.user_id', '=', 'users.id')
                            ->where([
                                ['mails.user_id', 'users.id'],
                                ['mails.name', 'Welcome Email']
                            ])->get(),
            ]);
    }
}

User.php :

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

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

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

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

    /**
     * Get the mails for a user.
     */
    public function mails()
    {
        return $this->hasMany(Mail::class);
    }
}

Mail.php :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Mail extends Model
{
    use HasFactory;

    /**
     * Get the user for a mail.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

2022_03_07_111014_create_mails_table.php :

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('mails', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained();
            $table->string('name');
            $table->string('object');
            $table->text('body');
            $table->timestamps();
        });
    }

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

我的数据库里也有5个用户,一个邮箱对应以下工厂:

    'user_id' => 3,
    'name' => 'Welcome Email',
    'object' => 'Bienvenu sur UH-Lawyers',
    'body' => $this -> faker -> text(200)

welcome.blade.php :

@component('mail::message')
Hello {{$name}},

@if (count($wMail)>0)
    @foreach($wMail as $mail)
        {{$mail->body}}
    @endforeach
@else 
    No result 
@endif

@component('mail::button', ['url' => ''])
Button Text
@endcomponent

Thanks,<br>
{{ config('app.name') }}
@endcomponent

因此,当我在 MySQL 上键入此查询时: SELECT body FROM Mails.mails join Mails.users on users.id = mails.user_id where users.id = mails.user_id and mails.name ="欢迎邮件"; 我有一行返回对应于我期望的邮件正文。但是当我在 Laravel 上发送邮件时,“无结果”出现在我的邮件正文中。 但是当我将 Laravel 的查询从 :

更改为

...->where([['mails.user_id', 'users.id'],...

至:

...->where([['mails.user_id', '3'],...

一切正常!!!我真的不明白问题是什么...

如果该查询适用于 MySQL,而您无法使用该语法使其在 laravel 中适用,您可以尝试使用 Laravel 的数据库 class,语法如下:

$awnser = DB::select('SELECT body FROM Mails.mails join Mails.users on users.id = mails.user_id where users.id = mails.user_id and mails.name ="Welcome Email"');

但是你应该使用参数而不是在那里写所有的东西:

$welcome = "Welcome Email";
$awnser = DB::select('SELECT body FROM Mails.mails join Mails.users on users.id = mails.user_id where users.id = mails.user_id and mails.name =:name', ['name' => $welcome]);

此解决方案可能适合您。

在您的 where 子句中,第一项过滤值 'users.id' 上的列 mails.user_id,它是一个字符串。

我猜这不是您打算做的。假设您要根据特定用户 ID 过滤该列,您需要提供该实际值。

通常,您可以使用 Auth::user()->id 检索当前(登录)用户的 ID。所以我建议您更新 build() 方法如下:

// Welcome.php

public function build()
{
    $currentUserId = Auth::user()->id;

    return $this->from('xxxxxx@yyy.com', 'John Doe')
        ->subject('Welcome')
        ->markdown('mails.welcome')
        ->with([
            'name' => 'New User',
            'wMail' => DB::table('mails')
                        ->join('users', 'mails.user_id', '=', 'users.id')
                        ->where('mails.user_id', '=', $currentUserId)
                        ->where('mails.name', '=', 'Welcome Email')
                        ->first(),
        ]);
}

但是,如果您希望传入另一个特定的用户 ID,则需要为此使用构造函数参数:

// Welcome.php
// (imports, traits and comments removed for brevity)

namespace App\Mail;

class Welcome extends Mailable
{
    // ...

    protected int $userId;


    public function __construct(int $userId)
    {
        $this->userId = $userId;
    }

    public function build()
    {
        return $this->from('xxxxxx@yyy.com', 'John Doe')
            ->subject('Welcome')
            ->markdown('mails.welcome')
            ->with([
                'name' => 'New User',
                'wMail' => DB::table('mails')
                    ->join('users', 'mails.user_id', '=', 'users.id')
                    ->where('mails.user_id', '=', $this->userId)
                    ->where('mails.name', '=', 'Welcome Email')
                    ->first(),
            ]);
    }
}

然后,当您创建 Welcome 可邮寄实例时:

$userId = 0; // TODO: Retrieve the user ID you need
Mail::to('your@recipient.here')->send(new Welcome($userId));

可以在该页面上找到相关文档:https://laravel.com/docs/9.x/mail#sending-mail