I have a "types" table which contains only ID and Name, the relation works on the first object but returns null on the following objects. Here is what my JSON looks like:
{"id":1,"type_id":1,"name":"test1","enabled":1,"measurement_type":{"id":1,"name":"test"}},
{"id":2,"type_id":2,"name":"test2","enabled":0,"measurement_type":null}]},
{"id":3,"type_id":1,"name":"test3","enabled":1,"measurement_type":null}]}
Here are my relations:
MeasurementFields Model
public function measurement_type() {
return $this->belongsTo(MeasurementType::class, 'type_id');
}
MeasurementTypes Model
public function measurement_type() {
return $this->belongsTo(MeasurementData::class);
}
In this Model I already have a measurement_field function which declares a belongsTo to MeasurementData (different Model) So, how do I name the new function with hasMany for types?
My Controller:
public function index()
{
return JsonResource::collection(MeasurementField::with('measurement_type')->get());
}
They all contain data, as you can see from the JSON, the relation just doesn't do anything with it.
My migrations:
Schema::create('measurement_types', function (Blueprint $table) {
$table->id()->autoincrement();
$table->string('name');
});
Schema::create('measurement_fields', function (Blueprint $table) {
$table->id()->autoincrement();
$table->foreignId('type_id')->constrained('measurement_types');
$table->string('name')->unique();
$table->boolean('enabled');
});
I think your measurement_type has many measurement_field.
and I guess you have to put this in your MeasurementField Model:
public function measurement_type() {
return $this->belongsTo(MeasurementType::class, 'type_id');
}
Related
i want fetch two tables data using with() but getting error as "Call to a member function addEagerConstraints() on null "
I have author model with multiple post relationship
My model relation as follows as follows:
Post relationship :
class Post extends Model
{
use HasFactory;
public function author(){
$this->belongsTo(Author::class);
}
}
Author model as follows:
class Author extends Model
{
use HasFactory;
public function post(){
return $this->hasMany(Post::class);
}
}
my migration of post table as follows:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('cat');
$table->timestamps();
$table->unsignedBigInteger('author_id');
$table->foreign('author_id')->references('id')->on('authors');
});
I am trying to fetch data in controller as follows using with() in postcontroller
public function index(){
return $data = Post::with('author')->get();
}
But getting error as Call to a member function addEagerConstraints() on null . Anyone have idea what is wrong in that then please let me know.
Can you try adding a return statement;
class Post extends Model
{
use HasFactory;
public function author(){
return $this->belongsTo(Author::class);
}
}
I was creating two tables user and user_info and i want to use the userid in userinfo.
I don't know how to use the userid in userinfocontroller.
You must define one to one relation in your models.
in User Model :
public function info()
{
return $this->hasOne(Info::class,'foreign key'); // (Info = your userinfo model)
}
and in your Info model :
public function user()
{
return $this->belongsTo(User::class, 'foreign key');
}
you can read documents too.
In the User Model
public function info()
{
return $this->hasOne(userinfo::class);
}
And in userinfo Model
public function user()
{
return $this->belongsTo(User::class);
'user_id'
}
Common question I guess, but I can't resolve it despite the informations I found online.
I've a sequence of hasMany relations :
User has many clients has many contracts has many materials.
I did my best but I find myself confronted to this error :
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
(SQL: create table clients (id int unsigned not null, user_id
int unsigne d null, ...) default character set utf8mb4 collate
utf8mb4_unicode_ci engine = InnoDB)
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key
constraint
Migrations :
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
// Keys
$table->increments('id');
// Other
...
$table->timestamps();
});
}
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('clients');
Schema::drop('users');
Schema::enableForeignKeyConstraints();
}
}
class CreateClientsTable extends Migration
{
public function up()
{
Schema::create('clients', function (Blueprint $table) {
$table->engine = 'InnoDB';
// keys
$table->unsignedInteger('id')->unique();
$table->primary('id');
$table->unsignedInteger('user_id')
->nullable();
$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade');
// others
...
});
}
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('contracts');
Schema::drop('clients');
Schema::enableForeignKeyConstraints();
}
}
class CreateContractsTable extends Migration
{
public function up()
{
Schema::create('contracts', function (Blueprint $table) {
$table->engine = 'InnoDB';
// Keys
$table->increments('id');
$table->string('contract_number')->unique();
$table->unsignedInteger('client_id');
$table->foreign('client_id')->references('id')->on('clients')
->onDelete('cascade');
// Others
...
});
}
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('materials');
Schema::drop('contracts');
Schema::enableForeignKeyConstraints();
}
}
class CreateMaterialsTable extends Migration
{
public function up()
{
Schema::create('materials', function (Blueprint $table) {
$table->engine = 'InnoDB';
// Keys
$table->increments('id');
$table->string('contract_number')->unique();
$table->unsignedInteger('contract_id');
$table->foreign('contract_id')->references('id')->on('contracts')
->onDelete('cascade');
// Others
...
});
}
public function down()
{
Schema::drop('materials');
}
}
What am I doing wrong ?
You should add ->unsigned() to all your key columns you have.
Please use this instead of unsignedInteger() and set the type to integer()
Are you sure that your migrations are running in the correct order? They should be running in the order you provided in your example code. I can't seem to recreate the error on my end using your exact example migrations.
The order is determined by the date at the beginning of the migration's filename. Alternatively, you could create all these tables in the same migration to force the order that way.
I am working on limiting access depending on user roles.
I want to be able to somehow override a belongsToMany relation to return all, if user->isAdmin() returns true.
Currently have as the AccountController index method:
public function index()
{
if(Auth::user()->isAdmin()) // can this go in beforeFilter?
return Account::all();
else
return Auth::user()->accounts;
}
in my User model:
public function accounts()
{
return $this->belongsToMany("Account");
}
Is there a neat way to do this without needing an if statement in the controller functions?
You cannot do this.
The relation method must return an instance of Relation, otherwise it throws an error.
There's nothing stopping you from creating a separate method for this:
AccountController.php:
public function index()
{
return Auth::user()->userAccounts();
}
User.php:
public function accounts()
{
return $this->belongsToMany("Account");
}
public function userAccounts()
{
if ($this->isAdmin()) return Account::all();
return $this->accounts;
}
I have two models with a one-to-many relationship.
class User extends ConfideUser {
public function shouts()
{
return $this->hasMany('Shout');
}
}
class Shout extends Eloquent {
public function users()
{
return $this->belongsTo('User');
}
}
This seem to work fine.
BUT, How do I get this to return the users object nested in the shout objects?
Right now it only returns all my Shouts, but I have no access in the JSON to the belonging user model.
Route::get('api/shout', function() {
return Shout::with('users')->get();
});
This just returns this JSON, with no user object for every shout:
[{"id":"1","user_id":"1","message":"A little test shout!","location":"K","created_at":"2013-05-23 19:51:44","updated_at":"2013-05-23 19:51:44"},{"id":"2","user_id":"1","message":"And here is an other shout that is a little bit longer...","location":"S","created_at":"2013-05-23 19:51:44","updated_at":"2013-05-23 19:51:44"}]
I was having the same trouble using Laravel 5. Just wanted to add that I got it to work by using the Model::with("relationship")->get() method on the model.
I figured it out.
The method needs to be named user() not users() when working with "belongsTo" relationship.
Makes sense.
And seems to work.
If you are using:
protected $visible = ['user'];
Don't forget to add there relationship, to be visible in JSON
u can use protected $with = ['users']; on Class Shout and use protected $with = ['shouts'];.
and Give Full namespace model name
class Shout extends Eloquent {
protected $with = ['users'];
public function users()
{
return $this->belongsTo('App\User');
}
}
and
class User extends ConfideUser {
protected $with = ['shouts'];
public function shouts()
{
return $this->hasMany('App\Shout');
}
}
Receive It
Route::get('api/shout', function() {
return Shout::all()->toJson;
});