【发布时间】:2016-04-19 04:44:11
【问题描述】:
我在尝试使用 Eloquent 模型执行真正基本的查询时遇到了麻烦,其中 create 和 find 都可以正常工作,但 where什么都不返回。
型号:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
protected $table = 'companies';
protected $fillable = ['name', 'ticker', 'industry', 'sector', 'description'];
protected $visible = ['name', 'ticker', 'industry', 'sector', 'description'];
}
控制器:
创建工作正常:
\App\Company::create(['ticker'=>'AAPL', 'name' => 'Apple Inc']);
在数据库上创建一个新行:
(身份证、姓名、股票代码)
1,苹果公司,苹果公司
查找工作正常:
$company = \App\Company::find(1);
print_r($company);
返回
App\Company 对象 ( [table:protected] => 公司 [fillable:protected] => 数组 ( [0] => 名称 [1] => 股票代码 [2] => 行业 [3] => 部门 [ 4] => 描述)[可见:受保护] => 数组([0] => 名称 [1] => 股票代码 [2] => 行业 [3] => 部门 [4] => 描述)[连接:受保护] => [primaryKey:protected] => id [perPage:protected] => 15 [incrementing] => 1 [timestamps] => 1 [attributes:protected] => Array ([id] => 1 [name] = > Apple Inc [股票代码] => AAPL [行业] => [部门] => [描述] => [created_at] => 2016-01-14 00:01:35 [updated_at] => 2016-01-14 00 :01:35 ) [original:protected] => Array ([id] => 1 [name] => Apple Inc [ticker] => AAPL [industry] => [sector] => [description] => [created_at ] => 2016-01-14 00:01:35 [updated_at] => 2016-01-14 00:01:35) [关系:受保护] => 数组 () [隐藏:受保护] => 数组 () [ appends:protected] => Array () [guarded:protected] => Array ([0] => *) [dates:protected] => Array () [dateFormat:protected] => [casts:protected ] => Array ( ) [touches:protected] => Array ( ) [observables:protected] => Array ( ) [with:protected] => Array ( ) [morphClass:protected] => [exists] => 1 [ wasRecentlyCreated] => )
现在,当我尝试按 id 以外的任何字段进行搜索时,它根本不会返回任何内容:
$company = \DB::table('companies')->select('ticker', 'name')->where('ticker', '=', 'AAPL')->get();
print_r($company);
返回一个空数组:
数组( )
两者都有:
$company = \App\Company::find(['ticker', 'AAPL'])->first();
print_r($company);
和:
$company = \App\Company::where('ticker', '=', 'AAPL')->first();
print_r($company);
它们根本什么都不返回。
---更新---
迁移:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCompaniesTable extends Migration
{
public function up()
{
Schema::create('companies', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('ticker');
$table->string('industry')->nullable();
$table->string('sector')->nullable();
$table->text('description')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::drop('companies');
}
}
【问题讨论】:
-
$company = DB::select( DB::raw("SELECT * FROM Companies WHERE ticker = :tickervar"), array('tickervar' => 'AAPL',));也不起作用......它返回一个空数组
-
您的
migration在这张桌子上看起来像什么?id是PK吗?我想是这样,但试图跳出框框思考。奇怪的是它不起作用。 -
建议:转储
App\Company::where('ticker', '=', 'AAPL')->toSql();的结果或安装github.com/barryvdh/laravel-debugbar 以查看查询是什么,然后直接针对您的数据库运行该查询。 -
你可以通过
App\Company::where('ticker', '=', 'AAPL')->getBindings();看到传递给?的值 -
@JuanSerrats 大写字母应该没什么区别,但是如果您从网页复制 AAPL,有时会有一些奇怪的字符被复制过来。零长度空格等
标签: php mysql eloquent laravel-5.2